[英]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.