COUNT DISTINCT WITH CONDITION 和 GROUP BY

COUNT DISTINCT WITH CONDITION and GROUP BY

我想根据特定条件计算列中不同项目的数量。例如,如果 table 是这样的:

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

如果我想将最后日期的状态不为空的不同名称的数量统计为“名称计数”,并按状态对它们进行分组,我应该怎么做?

结果应该是:

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)  

您可以尝试使用 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

您可以尝试使用以下查询

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;

这应该可行,但 true 的 name_count 是否应该为 2,因为 Andrew 和 Mary 的状态都为 true?至少这是我在 运行 我的命令

之后的回答
status | name_count
-------+-----------
false   | 1           
true  | 2         

如果您对命令的工作方式有任何疑问,请告诉我