I have the following table that I’m trying to find the total count for each unique name
element. The problem is, other: 1
and other: Null
are supposed to be different elements, but my query is grouping them together. The issue I’m running into is that null
is not being counted as a row. But when I use count(*)
, other: 1
and other: Null
are grouped together.
Name | id | GroupId |
---|---|---|
Other | 1 | 8 |
Other | Null | 8 |
2 | 8 | |
3 | 8 | |
2 | 8 |
The goal is to return:
[{Other: 1}, {Other: 1}, {Facebook: 2}, {Google: 1}]
I’ve tried:
SELECT name, count(id) FROM table WHERE id IS NOT NULL AND groupId='${id}' GROUP BY name UNION SELECT name, count(*) FROM table WHERE id IS NULL AND groupId ='${id}' GROUP BY name
And:
SELECT name, count(id) FROM table WHERE id='${id}' GROUP BY name
How would I get the desired return value above?
Advertisement
Answer
You seem to want one result row per name and ID, so don’t group by name only, but by name and ID:
SELECT name, COUNT(*) FROM table WHERE groupId = '${id}' GROUP BY name, id ORDER BY name, id;
As you don’t want to show the ID in your result, omit it from the select clause.