I have the following tables:
create table Users (
Id int
)
create table Vals1 (
UserId int,
Number int
)
create table Vals2 (
UserId int,
Number int
)
I have values in Vals1
and Vals2
but not a value for every UserId
. What I want to do is, when available, sum the corresponding values between Vals1
and Vals2
.
In this example, assume I have records with Id
1-5 in my User table. So, say I have the following in Vals1
:
UserId Number
1 10
2 15
4 20
And this in Vals2
:
UserId Number
1 30
2 55
3 40
This is what I want as output:
UserId Number
1 40
2 70
3 40
4 20
5 0
My first stab at this produces correct results, but this seems really ugly:
;WITH AllVals1 AS (
SELECT Id, ISNULL(Number, 0) as Number
FROM Users
LEFT JOIN Vals1 ON Id = UserId
), AllVals2 AS (
SELECT Id, ISNULL(Number, 0) as Number
FROM Users
LEFT JOIN Vals2 ON Id = UserId
)
SELECT v1.Id, v1.Number + v2.Number
FROM AllVals1 v1
JOIN AllVals2 v2 ON v1.Id = v2.Id
Is there a more succinct/efficient way of doing this?