Home > Mobile >  SQL Group by: Getting count of all distinct values in a column even if the count is zero
SQL Group by: Getting count of all distinct values in a column even if the count is zero

Time:01-28

I have two tables for which I am trying query in a certain way-

Table 1

ID Cust Type Status
1 A Active
2 B Active
3 A Active
4 A Active
5 B Inactive

Table 2

ID ID Type ID Type Value
1 Type 1 1234
1 Type 2 2345
1 Type 3 3456
2 Type 1 4567
2 Type 3 5678
2 Type 5 6789
3 Type 1 7890
3 Type 4 8901
4 Type 5 9012

I am trying to get the result like this - Result

ID Type Count of Active Cust Type A
Type 1 2
Type 2 1
Type 3 1
Type 4 1
Type 5 0

I have tried different kinds of joins and group by but for whatever reason I do not see the results for the ID type which have a count of 0. So in the example above, I would not see Type 5.

CodePudding user response:

You need the left on the Table1, you want all of those values. You can put more than * in the count operator.

select Table1.ID, count(Table2.ID) from Table1 left join Table2 on Table1.ID = Table2.ID group by Table1.ID

CodePudding user response:

Try this approach, valid in T-SQL (Sql Server) In practice you build 2 temporary tables and left-join them so the type without counts would return a null value and you can COALESCE it at 0

SELECT TYPES.[ID Type], COALESCE(COUNTS.TYPE_COUNT, 0)
FROM
(SELECT DISTINCT [ID Type] FROM TABLE2) TYPES
LEFT JOIN
(SELECT T2.[ID Type], COUNT(*) as TYPE_COUNT
FROM TABLE2
JOIN TABLE1
ON TABLE2.ID = TABLE1.ID
WHERE TABLE1.Status = 'Active') COUNTS
ON TYPES.[ID Type] = COUNTS.[ID Type]

I did not try this so it may contains some syntax error, but my goal is to give you the idea

CodePudding user response:

You need a LEFT JOIN between tab2 and tab1, and a COUNT aggregation.

SELECT tab2.ID_Type, COUNT(tab1.ID) AS Count_of_Active_Cust_Type_A
FROM      tab2 
LEFT JOIN tab1 ON tab2.ID = tab1.ID AND tab1.Cust_Type = 'A'
GROUP BY tab2.ID_Type

Output:

ID_Type Count of Active Cust Type A
Type 1 2
Type 2 1
Type 3 1
Type 4 1
Type 5 1

Check the MySQL demo and the SQLite demo.

Note: There's an active Cust Type A for Type 5 as well.

  •  Tags:  
  • sql
  • Related