Redshift 嵌套案例 when/ If then else
Redshift nested case when/ If then else
当一个语句有多个条件时,是否有嵌套 case when 语句的方法。例如下面,其中num_students = 2,有很多差异类。因此 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 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 or num_students is null then 'unk'
-- num_students must be 2
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)
是的,这是嵌套 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 子句 :)
当一个语句有多个条件时,是否有嵌套 case when 语句的方法。例如下面,其中num_students = 2,有很多差异类。因此 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 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 or num_students is null then 'unk'
-- num_students must be 2
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)
是的,这是嵌套 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 子句 :)