简体   繁体   中英

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? 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?

Although you could use coalesce() , the simplest method is an else clause:

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

SQL now supports an alternative syntax:

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

However, Snowflake does not (yet) support this.

As everybody else has noted, Snowflake sum gives ether NULL or a, and it works correctly.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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