Skip to content
Advertisement

SQL left join with 2 or more count group

My table

ID   catone   cattwo
100    2        1
100    3        1
200    1        2

expect result (count not sum)

ID    totalcat1    totalcat2
100     2             2
200     1             1

My query

  select COUNT(*) as totalcat1, catone  
  from Table1 
  group by cat1
  left join
  select COUNT(*) as totalcat2, cattwo  
  from Table1 
  group by cattwo

Try to have both count columns catone and cattwo
Not sure how to correct it. Thank you

Advertisement

Answer

A simple group-by should do it

select ID, COUNT(catone) as totalcat1, COUNT(cattwo) as totalcat2  
  from Table1 
  group by ID;

Note that this simply counts the number of values that are not NULL. If your original data was this…

ID   catone   cattwo
100    2        1
100    3        1
100    4        NULL

… then the result would be

ID    totalcat1    totalcat2
100     3             2

If you want to count the distinct values – so totalcat2 would be 1 (as only 1 value exists in that column, although it’s there twice) you could use

select ID, COUNT(DISTINCT catone) as totalcat1, COUNT(DISTINCT cattwo) as totalcat2  
  from Table1 
  group by ID;

which would return totalcat1 = 3 and totalcat2 = 1.

Here’s a db<>fiddle with the two options.

Here’s a second db<>fiddle on request of OP with ID 200.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement