繁体   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