显示GROUP BY中的所有值

时间:2010-09-16 12:35:14

标签: sql mysql

如何按语句获取组中的所有值?

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)

预期结果:

+------+----------+
| name | count(*) |
+------+----------+
| abc  |        2 | 
| xyz  |        0 | 
+------+----------+

2 个答案:

答案 0 :(得分:4)

您当前的解决方案会删除所有状态为A的记录,因此缺少名称xyz

这应该为您提供不同的名称和状态为A的记录数:

Select name, Sum( status = 'A' )
From mytable
Group By name;

这个通用的解决方案也适用于MySQL以外的其他数据库:

Select name, Sum( Case When status = 'A' Then 1 Else 0 End )
...

答案 1 :(得分:4)

你可以使用一个有趣的技巧,其中COUNT(列)计算非空值的数量;你也使用自联接(当这样做时):

SELECT a.name, COUNT(b.name)
  FROM mytable AS a LEFT OUTER JOIN mytable AS b
    ON a.name = b.name AND b.status = 'A'
 GROUP BY a.name;

这适用于所有版本的SQL;并非所有变体都允许您对布尔表达式求和,这在支持时无疑更快,更直接。

另一种写作方式是:

SELECT a.name, COUNT(b.name)
  FROM mytable AS a LEFT OUTER JOIN
       (SELECT name FROM mytable WHERE status = 'A') AS b
    ON a.name = b.name
 GROUP BY a.name;