【问题标题】:COUNT DISTINCT WITH CONDITION and GROUP BYCOUNT DISTINCT WITH CONDITION 和 GROUP BY
【发布时间】:2020-10-30 19:42:28
【问题描述】:

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

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)  

【问题讨论】:

  • 你的 dbms 是什么
  • 我正在使用 PostgreSQL

标签: sql if-statement group-by count distinct


【解决方案1】:
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         

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 老兄,你成功了! row_number() 是我的答案。非常感谢!!
    【解决方案3】:

    你可以试试下面的查询

    SELECT COUNT(DISTINCT Name), Status 
      FROM Table
      WHERE Status IS NOT NULL
     GROUP BY Status;
    

    【讨论】:

      猜你喜欢
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多