Lets say I have a table called census
with the following information:
COUNTRY PROVINCE CITY POPULATION
==============================================
USA California Sacramento 1234
USA California SanFran 4321
USA Texas Houston 1111
USA Texas Dallas 2222
Canada Ontario Ottawa 3333
Canada Manitoba Winnipeg 4444
I'm building a report at the country/province level, which gives me the following:
SELECT country, province, SUM(population)
FROM census
GROUP BY country, province;
COUNTRY PROVINCE SUM(POPULATION)
=======================================
USA California 5555
USA Texas 3333
Canada Ontario 3333
Canada Manitoba 4444
I'm looking to have an "overall summary" row included on the report, so that the final result looks like:
COUNTRY PROVINCE SUM(POPULATION)
=======================================
USA California 5555
USA Texas 3333
Canada Ontario 3333
Canada Manitoba 4444
TOTAL 16665
I'm acquainted with ROLLUP
s, but I can't seem to find a combination that gets me what I'm looking for. Using GROUP BY ROLLUP(country, province)
includes the total value I want, but it also includes a large number of extra values which I don't care about. This is also true with GROUP BY ROLLUP(country), province
How can I go about making the "total" record?
I'm currently calculating it with a UNION ALL
and repeating 90% of the first query with a different GROUP BY
, but because the first query is non-trivial, the result is slow and ugly code.
Here's a SQL Fiddle for those who want to play with this: http://sqlfiddle.com/#!4/12ad9/5