8

I have a particular question which is about MySQL. Please have a look at the query and the result set below:

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
----------------

I'd like to get the SUM of the COUNTs, so in this case I'd like to see '1412' in the next row, or in a new column, it doesn't really matter.

Any advice? I have tried to apply sub-queries to this but I couldn't find a proper solution.

Cheers

4 Answers 4

7

Does WITH ROLLUP do what you need?

SELECT 
      COUNT(c.Population) AS c, 
      c.City AS cc 
FROM City c 
GROUP BY c.City 
WITH ROLLUP;
Sign up to request clarification or add additional context in comments.

Comments

5

in the select statement, this should work (untested).

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;

Comments

0

On one row at the end:

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

ORDER BY c.City;

Comments

0

With simple 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;

John

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.