I have a query that looks more or less like this:
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
where Amount
is a currency (stored as a varchar, without a decimal), RemittingMember
is a link between the Items
table and the Member
table and RecordId
indicates what type of item the row is. In this case, a 50 is a debit and a 10 is a credit.
I need to subtract the first column from the second column and have that value in a third column. I know I can do this as follows:
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
But this is rather difficult to read and cumbersome to change if changes ever need to be made. I also know I can do this with local variables, but this is a report where a.Number
will change which will involve iteration which I want to avoid.
I also need to check the sign of this third column to put a value in a fourth column.
Is there a clever way of achieving this?