【问题标题】:Is it possible to COUNT the CONDITION and including NULL as well as the other values as 0?Is it possible to COUNT the CONDITION and including NULL as well as the other values as 0?
【发布时间】:2022-12-01 22:25:51
【问题描述】:

I have a problem. It includes the condition that to COUNT the rows where its status = 1 (GROUP BY name).

However, the result should include the rows WHERE those are not = 1 and NULL. And they are counted as 0.

I have tried cte, CASE WHEN, WHERE status = 1 or status IS NULL. It does include null as 0, but there are name containing 1 and 0 or only containing 0.

If I use WHERE status IS NULL OR status=1, the name with status 0 is not counted. If I use CASE WHEN status IS NULL THEN 0 WHEN status IS 0 THEN 0 WHEN status = 1 THEN COUNT(DISTINCT name) Then the name containing 1 AND 0 will be counted as 0.

【问题讨论】:

    标签: sqlite count


    【解决方案1】:

    You have to use CASE to get a 1 on the rows you want to count and 0 otherwise, then you have to SUM those values:

    SELECT name, 
           SUM(CASE WHEN status=1 THEN 1 ELSE 0 END) as status_count
    FROM table
    GROUP BY name
    

    【讨论】:

      猜你喜欢
      • 2022-12-01
      • 2022-12-02
      • 2022-12-26
      • 2022-12-02
      • 2020-06-24
      • 2022-11-09
      • 2021-08-21
      • 2022-12-27
      • 2022-12-01
      相关资源
      最近更新 更多