简体   繁体   English

COUNT DISTINCT WITH CONDITION 和 GROUP BY

[英]COUNT DISTINCT WITH CONDITION and GROUP BY

I want to count the number of distinct items in a column subject to certain conditions.我想根据某些条件计算列中不同项目的数量。 For example if the table is like this:例如,如果表是这样的:

ID | name   |    date    | status
---+--------+------------+--------
1  | Andrew | 2020-04-12 | true
2  | John   | 2020-03-22 | null
3  | Mary   | 2020-04-13 | null
4  | John   | 2020-05-27 | false
5  | Mary   | 2020-02-08 | true
6  | Andrew | 2020-02-08 | null

If I want to count the number of distinct names as "name count" where the last date's status is not null and group them by status, what should I do?如果我想将最后日期的状态不是 null 的不同名称的数量计为“名称计数”并按状态分组,我该怎么办?

The result should be:结果应该是:

status | name_count
-------+-----------
true   | 1            ---> Only counts Andrew (ID 1 has the last date)
false  | 1            ---> Only counts John (ID 4 has the last date)  

You can try using row_number()您可以尝试使用row_number()

select status,count(distinct name) as cnt from 
(
select name,date,status,row_number() over(partition by name order by date desc) as rn
from tablename
)A where rn=1 and status is not null
group by status

You can try with below query您可以尝试以下查询

SELECT COUNT(DISTINCT Name), Status 
  FROM Table
  WHERE Status IS NOT NULL
 GROUP BY Status;
SELECT status,COUNT(*) AS name_count 
FROM (SELECT DISTINCT status,name FROM TEMP WHERE status IS NOT NULL) 
GROUP BY status;

This should work but should the name_count of true be 2 since both Andrew and Mary have status as true?这应该可以,但是由于 Andrew 和 Mary 的状态都为 true,因此 true 的 name_count 是否应该为 2? Atleast here is my answer after I ran my command至少这是我运行命令后的答案

status | name_count
-------+-----------
false   | 1           
true  | 2         

Let me know if you have any doubts no how the command works如果您对命令的工作方式有任何疑问,请告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM