How do I get all the values in a group by statement?
mysql>select * from mytable;
+------+--------+--------+
| name | amount | status |
+------+--------+--------+
| abc | 12 | A |
| abc | 55 | A |
| xyz | 12 | B |
| xyz | 12 | C |
+------+--------+--------+
4 rows in set (0.00 sec)
mysql>select name, count(*) from mytable where status = 'A' group by name;
+------+----------+
| name | count(*) |
+------+----------+
| abc | 2 |
+------+----------+
1 row in set (0.01 sec)
Expected result:
+------+----------+
| name | count(*) |
+------+----------+
| abc | 2 |
| xyz | 0 |
+------+----------+
There’s a funny trick you can use where COUNT(column) counts the number of non-null values; you also use a self-join (when doing this):
This would work in all versions of SQL; not all variants will allow you to sum on a Boolean expression, which is undoubtedly faster and more direct when supported.
Another way to write it is: