[英]Conditional count using CASE WHEN
I have table like below 我有下面的表格
CID ITEM FLAG
C_1 ITEM_1 0
C_1 ITEM_2 1
C_1 ITEM_2 1
C_1 ITEM_2 0
C_2 ITEM_2 0
C_3 ITEM_2 1
C_3 ITEM_2 1
C_3 ITEM_3 1
and I want to produce table like 我想生产像
CID UNIQ_CNT_OF_CID
ITEM_1 0
ITEM_2 2
ITEM_3 1
The catch is - I want to count CID
once for same CID
. 美中不足的是-我想算
CID
为同一次CID
。
I tried , 我试过了 ,
SELECT ITEM, CID,
case when FLAG =1 then count(distinct CID) else 0 end as COUNTER
from T
group by ITEM
Please help !! 请帮忙 !!
I think I understand your question correctly, if not let me know. 我想我正确理解了你的问题,如果没有让我知道。
You can use a windowed function to accomplish this: 您可以使用窗口函数来完成此操作:
SELECT
ITEM,
COUNT(DISTINCT CID) OVER (PARTITION BY ITEM) AS UNIQ_CNT_OF_CID
FROM T
This will give you the same number of rows, so you if you want the unique from this, you can use a CTE or sub-query it like so: 这将为您提供相同数量的行,因此,如果您希望以此为唯一,则可以使用CTE或对其进行子查询,如下所示:
SELECT DISTINCT
ITEM, UNIQ_CNT_OF_CID
FROM
(
SELECT
ITEM,
COUNT(DISTINCT CID) OVER (PARTITION BY ITEM) AS UNIQ_CNT_OF_CID
FROM T
) final
You were close. 你近了 2 items to point out:
要指出的2个项目:
group by
must contain the same fields in the select (that are not in an aggregate function). group by
必须在select中包含相同的字段(不在聚合函数中)。 since there is no need to group by CID
, that should be removed from the select. CID
进行分组,因此应将其从选择中删除。 CASE
for fields not in a group by, but inside the aggregate function. CASE
用于不在分组依据中但在聚合函数中的字段。 So amending your SQL will now look like this: 因此,修改您的SQL现在将如下所示:
SELECT ITEM,
-- The CID is used inside the case, inside the count function.
-- NULL will not be included in the count
COUNT(DISTINCT CASE WHEN FLAG = 1 THEN CID ELSE NULL END) AS COUNTER
from T
group by ITEM
Result: 结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.