我有一个MSSQL查询,其中我正在使用grandtotal,这是通过获取SUM获得的值的SUM。
select
s.name
,SUM(b.dAmount) as total
,SUM(SUM(b.dAmount)) as grandtotal
from t_sales a
left outer join t_cust b on (b.dId=a.id)
where a.custId=@customerId
GROUP BY b.name;
我可以获得名称和总数,但是grandtotal不会返回任何值。请让我知道将SUM作为另一个值的SUM的正确方法是什么。谢谢
答案 0 :(得分:1)
试试这个:
select
b.name
,SUM(b.dAmount) as total
, SUM(SUM(b.dAmount)) OVER () as grandtotal
from t_sales a
left outer join t_cust b on (b.dId=a.id)
where a.custId=@customerId
GROUP BY b.name;
答案 1 :(得分:0)
在MySQL中,如果不使用嵌套子查询或使用GROUP BY WITH ROLLUP
对于您的情况,我建议您只使用WITH ROLLUP
关键字,这会在结果集中添加另一行总计。它还可以避免在集合的每一行返回相同的总数。
SELECT IFNULL(s.name, 'Total'), SUM(b.dAmount) as total
FROM t_sales a
LEFT OUTER JOIN t_cust b ON (b.dId = a.id)
WHERE a.custId = @customerId
GROUP BY b.name WITH ROLLUP;
如果您没有直接显示结果,可以删除IFNULL(s.name, 'Total')
位 - 超级聚合将在SUM()
答案 2 :(得分:0)
你也可以尝试这个
create table #t_sales (name varchar(100),amount numeric(18,2))
INSERT INTO #t_sales (name,amount)
values ('A',100.00)
,('B',200.00)
,('C',300.00)
,('C',400.00)
INSERT INTO #t_sales (name,amount)
values ('A',100.00)
,('B',200.00)
,('C',300.00)
,('C',400.00)
SELECT CASE WHEN (GROUPING(name) = 1) THEN 'GRAND TOTAL'
ELSE ISNULL(name, ' ')
END AS [type]
,SUM(amount) AS TOTAL
FROM #t_sales
GROUP BY name WITH ROLLUP