我创建了以下SQL查询
SELECT ae.[intEntitlementID]
,SUM(decIncrease) - SUM([decDecrease]) as quantity
,(SELECT SUM([decCredit]) - SUM([decDebit]) as value
FROM [tblMonetaryValueEvent]
where [intEntitlementID] = ae.intEntitlementID
and intSchemeYear <= @intSchemeYear
group by intEntitlementID) AS VALUE
,(SUM(decIncrease) - SUM([decDecrease])) *
(SELECT SUM([decCredit]) - SUM([decDebit]) as value
FROM [tblMonetaryValueEvent]
where [intEntitlementID] = ae.intEntitlementID
and intSchemeYear <= @intSchemeYear
group by intEntitlementID) AS TOTAL
FROM [tblAllocationEvent] ae
where ae.intBusinessID = @intBusinessID
and ae.intSchemeYear <= @intSchemeYear
group by ae.intEntitlementID
HAVING SUM(decIncrease) - SUM([decDecrease]) > 0
哪个返回以下内容
我现在需要在TOTAL列中找到两行的总和。
我希望输出以下数据。 73046.908322 + 1150.946103
有人对如何求和子查询返回的两个结果有任何提示吗?
谢谢
答案 0 :(得分:1)
使用ROLLUP
SELECT i, count(*) as c, sum(i) as s
FROM TEST
WHERE i<5
GROUP BY ROLLUP(i)
给予:
i c s
1 1 1
2 1 2
3 1 3
4 1 4
NULL 4 10
答案 1 :(得分:1)
正如@mkRabbani所说,您可以改善查询条件... 我想下一个可能是 -更具可读性 -表现更好(但我无法测试,因为没有数据)
所以,未经测试!:
WITH sums AS (
SELECT
ae.[intEntitlementID]
,SUM(decIncrease)-SUM(decDecrease) AS quantity
,SUM(decCredit)-SUM(decDebit) As value
FROM [tblAllocationEvent] ae
INNER JOIN [tblMonetaryValueEvent] ON [intEntitlementID] = ae.intEntitlementID
and intSchemeYear <= ae.intSchemeYear
where ae.intBusinessID = @intBusinessID
and ae.intSchemeYear <= @intSchemeYear
group by ae.intEntitlementID
)
SELECT
intEntitlementID
,quantity
,value
,quantity * value as Total
FROM sums