gpt4 book ai didi

sql - Redshift 嵌套情况 when/If then else

转载 作者:行者123 更新时间:2023-12-02 02:12:52 25 4
gpt4 key购买 nike

当一个条件有多个条件时,是否有一种嵌套 case when 语句的方法。例如下面的例子,其中 num_students = 2,有很多 diff 类。因此 num_of Students =2 的 else 语句是“Stu_2”,但对于整体数据来说是“unk”

select id, test_a, test_b,
case when num_students = 5 then 'Stu_5'
when num_students = 4 then 'Stu_4'
when num_students = 3 then 'Stu_3'
when num_students = 2 and class = 'Eng' then 'Stu_Eng_2'
when num_students =2 and class = 'Fre' then 'Stu_Fre_2'
when num_students = 2 and class = 'His' then 'Stu_His_2'
when num_students =2 and class = 'Geo' then 'Stu_Geo_2'
else 'Stu_2'
else 'unk'
from table

最佳答案

是的,这就是嵌套 case 语句的目的之一。嵌套时,需要再次调用CASE语句,如下:

select 
id,
test_a,
test_b,
case
when num_students = 5 then 'Stu_5'
when num_students = 4 then 'Stu_4'
when num_students = 3 then 'Stu_3'
when num_students = 2 then
case
when class = 'Eng' then 'Stu_Eng_2'
when class = 'Fre' then 'Stu_Fre_2'
when class = 'His' then 'Stu_His_2'
when class = 'Geo' then 'Stu_Geo_2'
else 'Stu_2'
end
else 'unk'
end as <column_name>
from <table_name>

不要忘记每个嵌套 CASE WHEN 之后的 END 子句:)

关于sql - Redshift 嵌套情况 when/If then else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67518075/

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