SQL查找匹配的条目,并在结果已存在具有ID的情况下返回相同的值。

huangapple go评论54阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年3月31日 22:35:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定