x table
id - name - balance
1 - test - 500
2 - test 2 - 400
3 - test 3 - 300
y table
idx - idy - name
1 - null
2 - 5
3 - null
4 - 6
SELECT x.Name, SUM(x.Balance)
FROM x
INNER JOIN y ON ???
if IS NULL y.idy ON (x.id = y.idx)
ELSE ON (x.id = y.idy)
我的英语不足以说明问题。但我的问题是可以理解的
答案 0 :(得分:1)
您可以使用下面的ISNULL:
SELECT x.Name, SUM(x.Balance)
FROM x
INNER JOIN y ON x.id = isnull(y.idy, y.idx)
group by x.Name
答案 1 :(得分:0)
布尔逻辑如下所示:
ON (y.idy IS NULL AND x.id = y.idx) OR (x.id = y.idy)
答案 2 :(得分:0)
试试这个:
SELECT x.Name,
SUM(x.Balance)
FROM x
INNER JOIN y
ON (y.idy IS NULL AND x.id = y.idx) OR (x.id = y.idy)
GROUP BY x.Name;
答案 3 :(得分:0)
您还可以尝试使用ANSI SQL标准''
函数来检查coalesce()
值
null
结果:
SELECT x.Name, SUM(x.Balance) [Balance] FROM x
join y ON coalesce(y.idy, y.idx) = x.id
group by x.Name