2

我有两个基本上像这样设置的表(非常精简的版本):

表 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 在第二个表中重复的次数。我没有连接这些表的主键。

任何帮助将不胜感激。

谢谢!

4

2 回答 2

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。有些人更喜欢 afull 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

关键是聚合必须在任何连接之前完成,所以你没有多行的问题。

于 2012-12-17T20:43:49.650 回答
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

这给了我你想要的输出

于 2012-12-17T20:47:38.840 回答