如何从 count() 中排除 0?在 sql?

How to exclude 0 from count()? in sql?

我有如下代码,我想计算给定时间段内的首次购买次数。我的销售 table 中有一列,如果买家不是首次购买者,则 is_first_purchase = 0

例如: buyer_id = 456391 已经是在 2 个不同日期购买过商品的现有买家。 因此 is_first_purchase 列将显示为 0,如下所示。

如果我在 is_first_purchase 上为这个 buyer_id = 456391 做一个 count() 那么它应该 return 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;

它return编辑了以下不是预期输出的内容

感谢有人可以帮助解释如何从计数中排除 is_first_purchase = 0,谢谢。

我认为您在需要 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;

您可以将查询简化为:

SELECT COUNT(*) AS 
FROM  sales no_of_first_purchases
WHERE is_first_purchase = 1
AND buyer_id = 456391 
AND date_id  BETWEEN '2021-02-01' AND '2021-03-01' 
ORDER BY 1 DESC;

能用WHERE完成的IF、CASE等函数最好避免使用

因为COUNT函数在值不是NULL(包括0)时才计数,如果不想计数,需要让CASE WHENreturn NULL

有两种方式可以算作你的期望值,一种是SUM另一种是COUNT但去掉else 0

的部分
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 

根据你的问题,我会将 CTE 和主要查询组合如下

select 
    COUNT(case when is_first_purchase = 1 then 1 end) as no_of_first_purchases 
from sales 
where buyer_id = 456391 
and date_id between '2021-02-01' and '2021-03-01' 
order by 1 desc;

Trino (f.k.a.Presto SQL) 最简单的方法是使用 aggregate with a filter:

count(name) FILTER (WHERE first_purchase = 'Yes') AS no_of_first_purchases