[英]How to exclude 0 from count()? in sql?
I have a code as below where I want to count number of first purchases for a given period of time.我有一个代码如下,我想计算给定时间段内的首次购买次数。 I have a column in my sales table where if the buyer is not a first time buyer, then 'is_first_purchase = 0"我的销售表中有一个列,如果买家不是首次购买者,则“is_first_purchase = 0”
For example: buyer_id = 456391 is already an existing buyer who made purchases on 2 different dates.例如:buyer_id = 456391 已经是在 2 个不同日期进行购买的现有买家。 Hence is_first_purchase column will show as 0 as per below.因此 is_first_purchase 列将显示为 0,如下所示。
If i do a count() on is_first_purchase for this buyer_id = 456391 then it should return 0 instead of 2.如果我对此买家 ID = 456391 在 is_first_purchase 上执行 count(),那么它应该返回 0 而不是 2。
My query as follows:我的查询如下:
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;
It returned the below which is not an intended output它返回了以下不是预期的输出
Appreciate if someone can help explain how to exclude is_first_purchase = 0 from the count, thanks.感谢有人可以帮助解释如何从计数中排除 is_first_purchase = 0,谢谢。
Because COUNT<\/code> function count when the value isn't
NULL<\/code> (include 0), if you don't want to count, need to let
CASE WHEN<\/code> return
NULL<\/code>
因为
COUNT<\/code>函数在值不为
NULL<\/code> (包括 0)时进行计数,如果不想计数,需要让
CASE WHEN<\/code>返回
NULL<\/code>
There are two ways you can count as your expectation, one is
SUM<\/code> other is
COUNT<\/code> but remove the part of
else 0<\/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
I think that you are using COUNT() when you want SUM().我认为您在需要 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.