[英]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()
使用rollup()
select country, count(*)
from customer
group by rollup (country )
If you want the label "Total" as well, you can use the grouping
function: 如果还需要标签“总计”,则可以使用grouping
功能:
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 在线示例: 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 您可以将另一列添加到名为Total的行中
DECLARE @Total int = 0;
SET @Total = (SELECT COUNT(*) FROM customer);
SELECT country, COUNT(*), [Total] = @Total
FROM customer
GROUP BY country
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.