我假设您在“如果 ID 仅在第二个表上,我想选择该行。如果 ID 在两个表中,我只想选择第二个表上的行”处有错字。这意味着您要始终从第二个表中选择,而不是从第三个表中选择。
所以我想如果有匹配的ID,你想从第三个中选择,否则使用第二个作为“后备”表。
您可以EXISTS
使用CASE
:
SELECT t1.IDCLIENT,
CASE WHEN EXISTS(SELECT 1 FROM dbo.Table3 t3
WHERE t3.IDCLIENT = t1.IDCLIENT)
THEN (SELECT TOP 1 t3.Value FROM dbo.Table3 t3
WHERE t3.IDCLIENT = t1.IDCLIENT)
ELSE (SELECT TOP 1 t2.Value FROM dbo.Table2 t2
WHERE t2.IDCLIENT = t1.IDCLIENT)
END AS Value
FROM dbo.Table1 t1
我想 SUM() VALUE 列上的值。
然后您可以在上面的查询中使用子查询,例如:
SELECT SUM(X.Value) FROM(
SELECT t1.IDCLIENT,
CASE WHEN EXISTS(SELECT 1 FROM dbo.Table3 t3
WHERE t3.IDCLIENT = t1.IDCLIENT)
THEN (SELECT TOP 1 t3.Value FROM dbo.Table3 t3
WHERE t3.IDCLIENT = t1.IDCLIENT)
ELSE (SELECT TOP 1 t2.Value FROM dbo.Table2 t2
WHERE t2.IDCLIENT = t1.IDCLIENT)
END AS Value
FROM dbo.Table1 t1
) X
Demo