我有一个看起来或多或少像这样的查询:
INSERT INTO #results
SELECT Name,
(SELECT
SUM(CAST(Amount AS BIGINT))
FROM Items
WHERE RemittingMember = a.Number
and RecordId = 50),
(SELECT SUM(CAST(Std_Amount AS BIGINT))
FROM Items
WHERE RemittingMember = a.Number
AND RecordId = 10)
FROM Member a
whereAmount
是一种货币(存储为 varchar,不带小数),是表和表RemittingMember
之间的链接,并指示该行是什么类型的项目。在这种情况下,50 是借方,10 是贷方。Items
Member
RecordId
我需要从第二列中减去第一列并将该值放在第三列中。我知道我可以这样做:
INSERT INTO #results
SELECT Name,
(SELECT
SUM(CAST(Amount AS BIGINT))
FROM Items
WHERE RemittingMember = a.Number
and RecordId = 50),
(SELECT SUM(CAST(Std_Amount AS BIGINT))
FROM Items
WHERE RemittingMember = a.Number
AND RecordId = 10),
(SELECT
SUM(CAST(Amount AS BIGINT))
FROM Items
WHERE RemittingMember = a.Number
and RecordId = 50) - (SELECT SUM(CAST(Std_Amount AS BIGINT))
FROM Items
WHERE RemittingMember = a.Number
AND RecordId = 10)
FROM Member a
但是,如果需要进行更改,这将很难阅读并且更改起来很麻烦。我也知道我可以使用局部变量来做到这一点,但这是一个a.Number
将发生变化的报告,其中将涉及我想要避免的迭代。
我还需要检查第三列的符号以将值放入第四列。
有没有聪明的方法来实现这一点?