【问题标题】:How to write a CASE statement that is inclusive of all conditions?如何编写包含所有条件的 CASE 语句?
【发布时间】:2020-11-16 20:13:06
【问题描述】:

我有一个类似的案例陈述:

case
    when invoice_net_amount <= 50 then '1. <= 50'
    when invoice_net_amount > 50 then '2. > 50'
    when invoice_net_amount > 250 then '3. > 250'
    when invoice_net_amount > 500 then '4. > 500'
end as user_revenue_tier

问题是所有用户都属于前两个桶。我希望invoice_net_amount &gt; 50 的用户显示在buckets 234 而不仅仅是2

有没有办法做到这一点?如果这很重要,我正在使用 Snowflake。

【问题讨论】:

  • 只用
  • case 表达式.
  • 在第一个'when'你测试50

标签: sql snowflake-cloud-data-platform


【解决方案1】:

你需要这样表述条件:

(case when invoice_net_amount <= 50  then '1. <= 50'
      when invoice_net_amount <= 250 then '2. > 50'
      when invoice_net_amount <= 500 then '3. > 250'
      else '4. > 500'
 end) as user_revenue_tier

case 表达式在第一个匹配条件处停止。因此,值 1000 与 &gt; 50 匹配,因此进入第二个条件。正如这个答案中所说,它属于else

【讨论】:

    【解决方案2】:

    CASE 表达式根据条件的顺序和第一个匹配“wins”进行评估:

    case   
        when invoice_net_amount > 500 then '4. > 500'
        when invoice_net_amount > 250 then '3. > 250'
        when invoice_net_amount > 50  then '2. > 50'
        when invoice_net_amount <= 50 then '1. <= 50'
    end as user_revenue_tier
    

    通过交换顺序,您将获得所需的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-19
      • 2012-09-13
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      相关资源
      最近更新 更多