在底部添加总计

时间:2017-01-11 21:38:33

标签: sql postgresql

我需要在表格的底部添加 Total 。这在我的场景中是否可行?

select country, count(*) from customer
group by country

Country         Count
  USA              5  
  UK              10
 Canada           15 
 Russia           25
                  55  (Requested from SO community) 

4 个答案:

答案 0 :(得分:4)

使用php-yt_downloader

rollup()

如果您还想要标签“Total”,可以使用select country, count(*) from customer group by rollup (country ) 功能:

grouping

在线示例:http://rextester.com/PKFE63954

答案 1 :(得分:2)

您可以使用

之类的东西人工生成一行
select country
    ,count(*) 
from customer
group by country

UNION ALL

SELECT 'Total'
    ,COUNT(*)
FROM customer

虽然这会影响您在此结果集上进行的任何计算,因为它是数据中的新行。

答案 2 :(得分:2)

类似的东西:

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

UNION

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

答案 3 :(得分:-1)

您可以在名为Total

的行中添加另一列
        DECLARE @Total int = 0;
        SET @Total = (SELECT COUNT(*) FROM customer);

        SELECT country, COUNT(*), [Total] = @Total
        FROM customer
        GROUP BY country