Reputation: 127
I need to add a Total at the bottom of my table. Is this possible in my scenario?
select country, count(*) from customer
group by country
Country Count
USA 5
UK 10
Canada 15
Russia 25
55 (Requested from SO community)
Upvotes: 2
Views: 4133
Reputation: 1539
something like:
SELECT country
, count(´1)
FROM customer
GROUP BY country
UNION
SELECT 'TOTAL'
, count(1)
FROM customer;
Upvotes: 2
Reputation:
Use rollup()
select country, count(*)
from customer
group by rollup (country )
If you want the label "Total" as well, you can use the grouping
function:
select case
when grouping(country) = 1 then 'Total'
else country
end as country,
count(*)
from customer
group by rollup (country )
Online example: http://rextester.com/PKFE63954
Upvotes: 4
Reputation: 514
You could add another column to the row named Total
DECLARE @Total int = 0;
SET @Total = (SELECT COUNT(*) FROM customer);
SELECT country, COUNT(*), [Total] = @Total
FROM customer
GROUP BY country
Upvotes: -1
Reputation: 114
You can artificially generate a row by using something like
select country
,count(*)
from customer
group by country
UNION ALL
SELECT 'Total'
,COUNT(*)
FROM customer
Although this will affect any future calculations you make on this result set as it is a new row in the data.
Upvotes: 2