在SQL查询中获取几个不同的计数

时间:2015-04-07 21:10:06

标签: mysql sql database

我正在进行此查询

SELECT zip, COUNT(*) AS amount 
FROM table
WHERE group_id = 19
GROUP BY zip ORDER BY amount DESC

这给了我一个列表,其中包含每个邮政编码的group_id 19次出现次数。但是我也想要每个zip的所有groups_id的总数(没有WHERE子句)。像这样(虚拟代码)

SELECT zip, COUNT(*) AS amount, COUNT(*) FOR THIS ZIP AS total, (amount/total * 100) AS percent
FROM table
WHERE group_id = 19
GROUP BY zip ORDER BY amount DESC 

这可能吗?

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

SELECT zip, COUNT(*) as amount, SUM(group_id = 19) AS grp19_amount,
       AVG(group_id = 19) as percent
FROM table
GROUP BY zip
ORDER BY grp19_amount DESC

答案 1 :(得分:0)

在SELECT查询中,您只能包含GROUP BY子句中包含的列或聚合函数的结果。所以COUNT(*)应该没问题,但是,(金额/总数* 100)将不起作用,除非你包括一个添加聚合函数,如SUM