英文:
SQL Find matching entries and return same value if result already exists with ID
问题
ID | Group | Result |
---|---|---|
1 | a | Blue |
1 | b | Blue |
2 | a | red |
2 | b | red |
2 | c | red |
3 | a | green |
3 | b | green |
3 | c | green |
3 | d | green |
英文:
So I am currently using a case function that looks at the group an entry is in and returns a result accordingly.
The code I am using looks something like this so far:
Case
when [Group] = 'b' or [Group] = 'e'
then "Blue"
when [Group] = 'c'
then "red"
when [ Group] = 'd'
then "green"
With that I am getting a table that looks like this
ID | Group | Result |
---|---|---|
1 | a | NULL |
1 | b | Blue |
2 | a | NULL |
2 | b | blue |
2 | c | red |
3 | a | NULL |
3 | b | blue |
3 | c | red |
3 | d | green |
I haven't included a line for when group = A because I only need that group to return it's own result when there's no matching results already. I need entries with the same ID to get categorized into the same result when returning specific values. Is there any way to have the code look for matching ID's and return those results as well given a certain priority level. For example, I need the table result to look as follows:
ID | Group | Result |
---|---|---|
1 | a | Blue |
1 | b | Blue |
2 | a | red |
2 | b | red |
2 | c | red |
3 | a | green |
3 | b | green |
3 | c | green |
3 | d | green |
答案1
得分: 0
如果我理解正确,您可以使用窗口函数和条件表达式:
选择 id,grp,
情况
当 max(case 当 grp = 'd' 然后 1 结束) over(partition 按 id) = 1 时 然后 '绿色'
当 max(case 当 grp = 'c' 然后 1 结束) over(partition 按 id) = 1 时 然后 '红色'
当 max(case 当 grp 在 ('b', 'e') 然后 1 结束) over(partition 按 id) = 1 时 然后 '蓝色'
结束 作为 结果
从 我的表
英文:
If I follow you correctly, you can use window functions and conditional expressions:
select id, grp,
case
when max(case when grp = 'd' then 1 end) over(partition by id) = 1 then 'green'
when max(case when grp = 'c' then 1 end) over(partition by id) = 1 then 'red'
when max(case when grp in ('b', 'e') then 1 end) over(partition by id) = 1 then 'blue'
end as result
from mytable
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论