任何人都可以帮助我获取查询以检索如下数据

时间:2016-10-31 18:18:19

标签: sql sql-server

    A                      B                   c

id   sal                 id  sal          id     sal
--------                 --------         -----------
1    100                  1  100           1     100
2    200                  2  200           2     200
3    300                  3  300           
4    400

输出应为:

id   sal
----------
1    300
2    600
3    600
4    400

3 个答案:

答案 0 :(得分:1)

以下是您要查找的确切结果的查询。

select 
    A.id, 
    sum(A.sal + ISNULL(B.sal, 0) + ISNULL(C.sal, 0) ) sal 
from TableA A
    left join TableB B 
        on A.id = B.id
    left join TableC C 
        on A.id = C.id
group by A.id

此外,如果TableC或TableB包含不在其他表中的记录,您可以使用以下代码:

select 
    IsNULL(A.id, IsNULL(B.id, C.id)) as id, 
    sum(ISNULL(A.sal, 0) + ISNULL(B.sal, 0) + ISNULL(C.sal, 0) ) sal 
from TableA A
    full outer join TableB B 
        on A.id = B.id
    full outer join TableC C 
        on A.id = C.id
group by IsNULL(A.id,IsNULL(B.id,C.id))

答案 1 :(得分:0)

select 
    x.id as id, 
    sum(x.sal) as sal  
from (
    select id as id, sal as sal from A
    union all
    select id as id, sal as sal from B
    union all
    select id as id, sal as sal from C
    ) as x
group by x.id

答案 2 :(得分:-2)

SELECT A.ID,
       SUM(ISNULL(A.SAL,0)+ISNULL(B.SAL,0)+ISNULL(C.SAL,0)) TOTAL 
FROM A left JOIN B ON A.ID=B.ID  
       left JOIN C ON B.ID=C.ID
GROUP BY A.ID