我的报告显示了客户订购的产品及其价格:
CompanyA Product 7 14.99
CompanyA Product 3 45.95
CompanyA Product 4 12.00
CompanyB Product 3 45.95
CompanyC Product 7 14.99
CompanyC Product 3 45.95
我想插入一行汇总每个公司的订单,如下所示:
CompanyA Product 7 14.99
CompanyA Product 3 45.95
CompanyA Product 4 12.00
Total: 72.94
CompanyB Product 3 45.95
Total: 45.95
CompanyC Product 7 14.99
CompanyC Product 3 45.95
Total: 60.94
这里有一些代码显示了我的查询的基本结构:
SELECT company
, product
, price
FROM companyMaster
ORDER BY company,
, product,
, price;
有谁知道怎么做?我在Transact-SQL(Microsoft SQL Server)中写这个。
答案 0 :(得分:4)
SELECT company,
product,
SUM(price)
FROM companyMaster
GROUP BY
company, ROLLUP(product)
答案 1 :(得分:3)
感谢大家的反馈/帮助,至少让我想到了不同的方法。我想出了一些不依赖于我正在使用的SQL Server版本的东西(我们的供应商经常更改版本,所以我必须尽可能地交叉兼容)。
这可能被认为是黑客攻击(好吧,这是一个黑客攻击)但是它可行,并且它完成了工作:
SELECT company
, product
, price
FROM companyMaster
ORDER BY company,
, product,
, price
UNION
SELECT company + 'Total'
, ''
, SUM(price)
FROM companyMaster
GROUP BY company
ORDER BY company;
此解决方案基本上使用两个select语句的UNION。第一个与原点完全相同,第二个产生我需要的总和线。为了正确定位总和,我在公司名称上添加了一个字符串连接(附加单词'Total'),这样当我按字母顺序对公司名称进行排序时,Total行将显示在每个公司部分的底部。
这是最终报告的样子(不完全是我想要的,但在功能上相同,只是看起来不是很漂亮:
CompanyA Product 7 14.99
CompanyA Product 3 45.95
CompanyA Product 4 12.00
CompanyA Total 72.94
CompanyB Product 3 45.95
CompanyB Total 45.95
CompanyC Product 7 14.99
CompanyC Product 3 45.95
CompanyC Total 60.94
答案 2 :(得分:2)
由于您使用的是SQL Server 2005,因此需要使用rollup这样的内容。
-- cte for test data
;with companyMaster(company, product, price) as
(select 'CompanyA', 'Product 7', 14.99 union all
select 'CompanyA', 'Product 3', 45.95 union all
select 'CompanyA', 'Product 4', 12.00 union all
select 'CompanyB', 'Product 3', 45.95 union all
select 'CompanyC', 'Product 7', 14.99 union all
select 'CompanyC', 'Product 3', 45.95
)
select
company,
case when grouping(product) = 0
then product
else 'Total:'
end,
sum(price)
from companyMaster
group by company, product with rollup
having grouping(company) = 0