将两个表中不相关的列相加,然后根据ID进行连接

时间:2012-12-17 20:35:23

标签: sql sql-server-2008-r2

我基本上设置了两个表(极简版):

表1

ID       Amt 1     Amt 2
-------------------------    
112     $20        $30
112     $50        $60
125     $75        $05

表2

ID       Amt 3     Amt 4
-------------------------
112       $25       $30
125       $40       $60
125      $110      $120

所有金额列需要单独求和,输出类似于:

查询结果:

ID       Amt 1     Amt 2     Amt 3     Amt 4
--------------------------------------------
112     $70        $90       $25       $30
125     $75        $05       $150      $180

我尝试过的联接导致记录重复(和求和)一个因子ID在第二个表中重复的次数。我没有连接这些表的主键。

非常感谢任何帮助。

谢谢!

2 个答案:

答案 0 :(得分:0)

要正确解决此问题,您需要单独进行聚合。即使两个表具有相同ID的多个行,这也将起作用:

select id, sum(amt1), sum(amt2), sum(amt3), sum(amt4)
from ((select id, sum(amt1) as amt1, sum(amt2) as amt2, NULL as amt3, NULL as amt4
       from tbl1
       group by id
      ) union all
      (select id, NULL, NULL, sum(amt3), sum(amt4)
       from tbl2
       group by id
      )
     ) t
group by id

上面的查询给出了group by的想法。有些人为此目的更喜欢full outer join

select coalesce(t1.id, t2.id) as id, amt1, amt2, amt3, amt4
from (select id, sum(amt1) as amt1, sum(amt2) as amt2
       from tbl1
       group by id
      ) t1 full outer join
      (select id, sum(amt3) as amt3, sum(amt4) as amt4
       from tbl2
       group by id
      ) t2
      on t1.id = t2.id

关键是聚合必须在任何连接之前完成,因此您不会遇到多行问题。

答案 1 :(得分:0)

在SQL Server 2005或更高版本上,您可以使用两个CTE(公用表表达式)对每个表进行求和/分组,然后加入两个 - 如下所示:

;WITH CTE1 AS
(
    SELECT 
        ID, Amount1 = SUM(Amt1), Amount2 = SUM(Amt2)
    FROM
        dbo.SumTbl1
    GROUP BY
        ID  
),
CTE2 AS
(
    SELECT 
        ID, Amount3 = SUM(Amt3), Amount4 = SUM(Amt4)
    FROM
        dbo.SumTbl2
    GROUP BY
        ID  
)
SELECT CTE1.ID, Amount1, Amount2, Amount3, Amount4
FROM CTE1
INNER JOIN CTE2 ON CTE1.ID = CTE2.ID

这为我提供了所需的输出