简体   繁体   中英

Add a total at the bottom

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) 

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

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.

something like:

SELECT country
    , count(´1)
FROM customer
GROUP BY country

UNION

SELECT 'TOTAL'
    , count(1)
FROM customer;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM