MySQL Group by - Get columns with zero count

后端 未结 3 1913
一生所求
一生所求 2021-01-14 03:29

I tried decrying other answers, no luck, hence asking.

I have one table and few more similar to this for other year Here is the table structure

--         


        
相关标签:
3条回答
  • 2021-01-14 04:03

    The COUNT is only returning the COUNT for the status that he finds for Microsoft. And those are Denied and Wthdrawn. You have to feed the query all the statuses and COUNT the occurrences of all of them. The ones that don't appear will in the table will be left with 0:

    SELECT a.STATUS, 
          SUM(CASE 
            WHEN b.STATUS IS NOT NULL
              THEN 1
            ELSE 0
          END) AS StatusCount
    FROM (
      SELECT DISTINCT STATUS
      FROM tab1
      ) a
    LEFT JOIN tab1 b ON a.STATUS = b.STATUS AND b.CompanyName = 'Microsoft'
    GROUP BY a.STATUS;
    

    What this does is:

    SELECT DISTINCT STATUS
    FROM tab1
    

    This finds all the statuses possible. If you have a reference table with all the possible statuses, even better Use it instead of this query.

    Then you do a LEFT JOIN on this table by status and companyName. This way, you will only get a match in STATUS if there is a record on the table. If there is, you add 1 to the SUM, otherwise you Add 0.

    sqlfiddle demo

    0 讨论(0)
  • 2021-01-14 04:05

    A fairly straight forward way is to get all distinct statuses and LEFT JOIN with the table to get the counts;

    SELECT a.status, COUNT(b.status) cnt
    FROM (SELECT DISTINCT status FROM Table1) a
    LEFT JOIN Table1 b
      ON a.status = b.status
     AND b.`Company name`='Microsoft'
    GROUP BY a.status
    

    An SQLfiddle to test with.

    0 讨论(0)
  • 2021-01-14 04:06

    You can nest a query, and search for when the Count is equal or greater than zero:

    SELECT a.status, a.stat_count FROM (SELECT status, count(*) as stat_count FROM table where company like '%Google%' GROUP BY status) a WHERE a.stat_count >= 0

    0 讨论(0)
提交回复
热议问题