SQL子查询返回的两行之和
我创建了以下SQL查询SQL子查询返回的两行之和,sql,sql-server,sum,subquery,Sql,Sql Server,Sum,Subquery,我创建了以下SQL查询 SELECT ae.[intEntitlementID] ,SUM(decIncrease) - SUM([decDecrease]) as quantity ,(SELECT SUM([decCredit]) - SUM([decDebit]) as value FROM [tblMonetaryValueEvent] where [intEntitlement
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
选择ae。[intEntitlementID]
,总和(减少)-总和(减少)作为数量
,(选择SUM([decCredit])-SUM([DecDecDebt])作为值
来自[TBLMonentaryValueEvent]
其中[IntentTitlementId]=ae.IntentTitlementId
和intSchemeYear使用
正如@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
,总和为(
挑选
ae.[intEntitlementID]
,总和(减少)-总和(减少)作为数量
,SUM(decredit)-SUM(decredit)作为值
来自[tblAllocationEvent]ae
[IntentTitlementId]=ae.IntentTitlementId上的内部联接[tblMonetaryValueEvent]
intSchemeYear“我现在需要在TOTAL列中添加这两行,但我在这方面遇到了困难。”意思是?我们无法访问您的数据,您也没有向我们显示所需的结果。您的脚本还有很多需要改进的地方。您可以发布一些具有预期输出的示例数据吗?这会有所帮助。抱歉,所需的结果现在已添加到正文和下面。我所需的结果是73046.908322和1150.946103的总和
i c s
1 1 1
2 1 2
3 1 3
4 1 4
NULL 4 10
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