繁体   English   中英

SQL 组并在新行求和

[英]SQL group and summing at new row

我有一个问题,我试图创建一个新的“行”(不是数据库的一部分),它只给我“计数”列的总和。 我想知道这是否可能?

我尝试将 SUM(count(cost) 添加为“总产品成本”OVER() AS Total_Count; 但这只会创建一个新列,每行显示的总和为 550.00。我希望 550.00 位于底部该列的最终计数。

select product, count(cost) as 'total product cost'

from product_Table

where product_Tier = 'grocery'

and as_of_date = '8/13/2020'

Group By product

Results:

product   total product cost
corn       250.00
tomatoes   300.00
SUM        550.00          <--trying to create a row like this.

select product, count(cost) as 'total product cost'
from product_Table
where product_Tier = 'grocery'
  and as_of_date = '8/13/2020'
Group By product
union 
select product,sum(cost)
from product_Table
where product_Tier = 'grocery'
  and as_of_date = '8/13/2020'
Group By product;

大多数数据库都支持标准的grouping sets功能:

select coalesce(product, 'Total'), count(cost) as totalproductcost
from product_Table
where product_Tier = 'grocery' and
      as_of_date = '2020-08-13'
group by grouping sets ( product, () );

一些数据库支持rollup但不支持grouping sets 语法可能会有所不同,但类似于:

select coalesce(product, 'Total'), count(cost) as totalproductcost
from product_Table
where product_Tier = 'grocery' and
      as_of_date = '2020-08-13'
group by product with rollup;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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