我有以下表格:
create table Users (
Id int
)
create table Vals1 (
UserId int,
Number int
)
create table Vals2 (
UserId int,
Number int
)
我在Vals1
和Vals2
中有值,但不是每个UserId
的值。我想要做的是,在可用时,将Vals1
和Vals2
之间的相应值相加。
在此示例中,假设我的User表中有Id
1-5的记录。所以,我在Vals1
中有以下内容:
UserId Number
1 10
2 15
4 20
这是Vals2
:
UserId Number
1 30
2 55
3 40
这就是我想要的输出:
UserId Number
1 40
2 70
3 40
4 20
5 0
我对此的第一次尝试产生了正确的结果,但这看起来真的很难看:
;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
有更简洁/有效的方法吗?
答案 0 :(得分:2)
这是一种更简单的方法,只有在Vals1
和Vals2
表中每个ID有1行时才会有效。
SELECT id, COALESCE(v1.Number, 0) + COALESCE(v2.Number, 0) as NumberSum
FROM users u
LEFT OUTER JOIN Vals1 AS v1
ON u.id = v1.userid
LEFT OUTER JOIN vals2 AS v2
ON u.id = v2.userid
如果值表中每个ID超过1行,则可以添加SUM()
和GROUP BY
子句以删除多行。
SELECT id
,SUM(COALESCE(v1.Number, 0) + COALESCE(v2.Number, 0))
FROM users u
LEFT OUTER JOIN Vals1 AS v1
ON u.id = v1.userid
LEFT OUTER JOIN vals2 AS v2
ON u.id = v2.userid
GROUP BY id
答案 1 :(得分:1)
您可以使用左连接,然后使用coalesce或isnull
来计算空值SELECT users.id, ISNULL(vals1.number,0) + ISNULL(vals2.number,0) as [sum]
FROM users
left join vals1 on vals1.userid = users.id
left join vals2 on vals2.userid = users.id
答案 2 :(得分:0)
我建议首先选择派生临时表中的所有值,然后按用户计算总和分组:
SELECT
tmp.UserId,
sum(tmp.Number) as Number
FROM
(SELECT
UserId,
Number
FROM
Vals1
UNION ALL
SELECT
UserId,
Number
FROM
Vals2) tmp
GROUP BY
tmp.UserId