简体   繁体   English

在 snowflake 中使用 SUM function 时,有没有办法返回零而不是空字符串?

[英]Is there a way to return zero vs. an empty string when using the SUM function in snowflake?

What would be the best way to display zero (0) or null vs. empty when using the sum function in snowflake/sql?在 snowflake/sql 中使用总和 function 时,显示零 (0) 或 null 与空的最佳方式是什么? For instance, I'm getting an empty string when sum equals zero when doing the following: sum(case when t.Status='Done' then 1 end) What am I missing?例如,当执行以下操作时总和等于零时,我得到一个空字符串: sum(case when t.Status='Done' then 1 end)我错过了什么?

Although you could use coalesce() , the simplest method is an else clause:尽管您可以使用coalesce() ,但最简单的方法是使用else子句:

sum(case when t.Status = 'Done' then 1 else 0 end)

SQL now supports an alternative syntax: SQL 现在支持替代语法:

count(*) filter (where t.Status = 'Done')

However, Snowflake does not (yet) support this.然而,Snowflake 不(还)支持这一点。

As everybody else has noted, Snowflake sum gives ether NULL or a, and it works correctly.正如其他人所指出的,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); 

giving:给予:

THIS_IS_NULL   THIS_IS_ZERO   THIS_IS_ONE   THIS_IS_ALSO_ZERO
<null>         0              1             0

so if you are getting an empty string, as your output it is because you are using the output of SUM to do string manipulation, and have something wrong.所以如果你得到一个空字符串,如你的 output ,那是因为你正在使用 SUM 的 output 来进行字符串操作,并且有问题。

Taking your example from your comment, and expanding it to make sense...从您的评论中以您的例子为例,并将其扩展为有意义......

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;

gives what seems like correct results:给出看似正确的结果:

DATE    WEEK_START  TASK_STATUS
2020    2020-05-04  1
2020    2020-03-30  0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM