如何解决SQL组并在新行求和
我遇到一个问题,我试图创建一个新的“行”(不属于数据库的一部分),该行仅给我“计数”列的总和。我想知道这是否可能?
我尝试将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,count(cost) as totalproductcost
from product_Table
where product_Tier = 'grocery' and
as_of_date = '2020-08-13'
group by product with rollup;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。