簡體   English   中英

"<i>How to exclude 0 from count()?<\/i>如何從 count() 中排除 0?<\/b> <i>in sql?<\/i>在 sql?<\/b>"

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM