gpt4 book ai didi

sql - 与 join 一起使用时,Case 返回多个值

转载 作者:行者123 更新时间:2023-11-29 14:31:24 25 4
gpt4 key购买 nike

我在使用 case 和 join together in redshift 时遇到问题(这不是我的真实数据,它只是为了示例,所以 max 对我没有帮助)。这是我的查询:

select a.num1, 
(case when b.param = 'd' then b.param
when b.param = 'c' then b.param
when b.param = 'b' then b.param
when b.param = 'a' then b.param end)
from table a inner join table b on a.num1 = b.num1

对于表a:

enter image description here

对于表b:

enter image description here

我得到的结果是:

enter image description here

但我只想为每个“num1”获取案例的第一个匹配项,例如:

enter image description here

我怎样才能做到这一点?谢谢!

最佳答案

对于这个数据,你可以使用max():

select a.num1, 
max(case when b.param = 'd' then b.param
when b.param = 'c' then b.param
when b.param = 'b' then b.param
when b.param = 'a' then b.param
end)
from table a inner join
table b
on a.num1 = b.num1
group by a.num1;

这可以简化为:

select a.num1, max(b.param)
from table a inner join
table b
on a.num1 = b.num1
group by a.num1;

这回答了您提出的问题。这可能无法解决您的实际问题。我建议您问另一个问题,使用更合适的样本数据和更好地描述您想做什么。

关于sql - 与 join 一起使用时,Case 返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51285300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com