[英]Is there a way to return zero vs. an empty string when using the SUM function in snowflake?
在 snowflake/sql 中使用总和 function 时,显示零 (0) 或 null 与空的最佳方式是什么? 例如,当执行以下操作时总和等于零时,我得到一个空字符串: sum(case when t.Status='Done' then 1 end)
我错过了什么?
尽管您可以使用coalesce()
,但最简单的方法是使用else
子句:
sum(case when t.Status = 'Done' then 1 else 0 end)
SQL 现在支持替代语法:
count(*) filter (where t.Status = 'Done')
然而,Snowflake 不(还)支持这一点。
正如其他人所指出的,Snowflake sum 给出了以太币 NULL 或 a,并且它工作正常。
select
sum(case when Status='Done' then 1 end) as this_is_null
,sum(case when Status='Done' then 1 else 0 end) as this_is_zero
,sum(case when Status='None' then 1 else 0 end) as this_is_one
,sum(iff(status='Done', 1, 0)) as this_is_also_zero
from values ('None') tmp(status);
给予:
THIS_IS_NULL THIS_IS_ZERO THIS_IS_ONE THIS_IS_ALSO_ZERO
<null> 0 1 0
所以如果你得到一个空字符串,如你的 output ,那是因为你正在使用 SUM 的 output 来进行字符串操作,并且有问题。
从您的评论中以您的例子为例,并将其扩展为有意义......
SELECT left(t.date_task,4) as date
,left(DATE_TRUNC('week', t.date_task),10) as week_start
,sum(case when t.status='Done' then 1 else 0 end) as task_status
FROM (
select to_timestamp_ntz(date_task) as date_task, status
from values ('2020-05-05', 'Done'),('2020-04-05', 'None') v(date_task, status)
) t
GROUP BY 1,2;
给出看似正确的结果:
DATE WEEK_START TASK_STATUS
2020 2020-05-04 1
2020 2020-03-30 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.