[英]How to exclude 0 from count()? in sql?
我有一個代碼如下,我想計算給定時間段內的首次購買次數。 我的銷售表中有一個列,如果買家不是首次購買者,則“is_first_purchase = 0”
例如:buyer_id = 456391 已經是在 2 個不同日期進行購買的現有買家。 因此 is_first_purchase 列將顯示為 0,如下所示。
如果我對此買家 ID = 456391 在 is_first_purchase 上執行 count(),那么它應該返回 0 而不是 2。
我的查詢如下:
with first_purchases as
(select *,
case when is_first_purchase = 1 then 'Yes' else 'No' end as first_purchase
from sales)
select
count(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
from first_purchases
where buyer_id = 456391
and date_id between '2021-02-01' and '2021-03-01'
order by 1 desc;
它返回了以下不是預期的輸出
感謝有人可以幫助解釋如何從計數中排除 is_first_purchase = 0,謝謝。
因為
COUNT<\/code>函數在值不為
NULL<\/code> (包括 0)時進行計數,如果不想計數,需要讓
CASE WHEN<\/code>返回
NULL<\/code>
有兩種方法可以算作您的期望,一種是
SUM<\/code> ,另一種是
COUNT<\/code> ,但刪除
else 0<\/code>的部分
SUM(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
COUNT(case when first_purchase = 'Yes' then 1 end) as no_of_first_purchases
我認為您在需要 SUM() 時使用的是 COUNT()。
with first_purchases as
(select *,
case when is_first_purchase = 1 then 'Yes' else 'No' end as first_purchase
from sales)
select
SUM(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
from first_purchases
where buyer_id = 456391
and date_id between '2021-02-01' and '2021-03-01'
order by 1 desc;
Trino(fka Presto SQL)最簡單的方法是使用帶有過濾器的聚合<\/a>:
count(name) FILTER (WHERE first_purchase = 'Yes') AS no_of_first_purchases
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.