Sql server T-SQL:无法对包含聚合或子查询的表达式执行聚合函数
我试图将某个金额的合计结果相加,并将其减至合计,但我发现以下错误:Sql server T-SQL:无法对包含聚合或子查询的表达式执行聚合函数,sql-server,tsql,Sql Server,Tsql,我试图将某个金额的合计结果相加,并将其减至合计,但我发现以下错误: Select SUM (( (select SUM (amount) FROM transfer tr1 where transfer_type = 'Positive' group by transfer_id) EXCEPT (SELECT SUM (amount) from transfer tr2 where transfer_type = 'Negative' group b
Select SUM ((
(select SUM (amount) FROM transfer tr1
where transfer_type = 'Positive' group by transfer_id)
EXCEPT
(SELECT SUM (amount) from transfer tr2
where transfer_type = 'Negative' group by transfer_id)))
想象一下这样的事情
第一个子查询:1 3 5 7
第二个子查询:246
总计:(1+3+5+7)-(2+4+6)=4
这是我的查询,但正如我所说,我看到以下错误:
Select SUM ((
(select SUM (amount) FROM transfer tr1
where transfer_type = 'Positive' group by transfer_id)
EXCEPT
(SELECT SUM (amount) from transfer tr2
where transfer_type = 'Negative' group by transfer_id)))
如何转换查询以不看到错误:
无法对包含聚合或子查询的表达式执行聚合函数
非常感谢您提前您可以构建一个查询,将
的“负”值的加法转换为减法,如下所示:
SELECT
transfer_id
, SUM (
CASE 'transfer_type'
WHEN 'Positive' THEN amount
WHEN 'Negative' THEN -amount
ELSE NULL
END
) AS total
FROM transfer
GROUP BY transfer_id
现在使用单个和
,加法符号由大小写
表达式控制