Redshift 嵌套情况when/If then else

IOI*_*IOI 2 sql amazon-redshift

当有多个条件时,是否有一种嵌套 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
Run Code Online (Sandbox Code Playgroud)

Ale*_* CC 5

是的,这就是嵌套 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>
Run Code Online (Sandbox Code Playgroud)

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