sql - 在底部添加总计

标签 sql postgresql

我需要在表格底部添加一个总计。这在我的场景中可能吗?

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

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

最佳答案

使用rollup()

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

如果你还想要标签“Total”,你可以使用grouping函数:

select case 
          when grouping(country) = 1 then 'Total' 
          else country 
       end as country, 
       count(*) 
from customer
group by rollup (country )

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

关于sql - 在底部添加总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41601153/

相关文章:

mysql - 如何确保两行不具有相同的值

django - 在 django 1.11 中,如何允许用户登录只读数据库?

postgresql - 如何在 Ecto 片段语句中使用带时区的 date_trunc

mysql - postgresql 正在将更新增加 2?

sql-server - PostgreSQL 等同于 SQL Server GROUP BY WITH ROLLUP

mysql - 更新语句给出未知列错误

mysql - 如何在1个查询中将innerjoin查询与2个LCASE + REPLACE结合起来?

sql - 无法删除表 SQL 错误 : ORA-00600

sql - 子查询的结果可以与自身连接吗?

sql - 在 postgres json 数组中查找单个元素