MySQL COUNT(),SUM()和GROUP BY

时间:2011-09-28 16:01:58

标签: mysql

我有一个关于MySQL的特殊问题。请查看下面的查询和结果集:

SELECT COUNT(c.Population) AS c, c.City AS cc
FROM City c
GROUP BY c.City
ORDER BY c.City;

261 | Bristol
----------------
910 | London
----------------
241 | Manchester
----------------

我想获得COUNT的总和,所以在这种情况下,我希望在下一行或新列中看到'1412',这并不重要。

有什么建议吗?我试图对此应用子查询,但我找不到合适的解决方案。

干杯

4 个答案:

答案 0 :(得分:7)

WITH ROLLUP能做你需要的吗?

SELECT 
      COUNT(c.Population) AS c, 
      c.City AS cc 
FROM City c 
GROUP BY c.City 
WITH ROLLUP;

答案 1 :(得分:5)

在select语句中,这应该有效(未经测试)。

SELECT 
    COUNT(c.Population) AS c, 
    c.City AS cc, 
    (SELECT COUNT(c.Population) FROM City) as TotalPop 
FROM City c 
GROUP BY c.City 
ORDER BY c.City;

答案 2 :(得分:0)

最后一行:

SELECT *
  FROM
(
    SELECT 0 as total
         , COUNT(c.Population) AS c
         , c.City AS cc
      FROM City c GROUP BY c.City

     union

    SELECT 1 as total
         , COUNT(c.Population) AS c
         , null AS cc
      FROM City
) myquery
ORDER BY total
       , city

订购c.City;

答案 3 :(得分:0)

使用简单的UNION;

select count(d.Population) as c, 'TOTAL' as cc from City d

union

SELECT COUNT(c.Population) AS c, c.City AS cc
FROM City c
GROUP BY c.City
ORDER BY c.City;

约翰