简体   繁体   English

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

[英]Summing unrelated columns in two tables, then joining based on an ID

I have two tables set up basically like this (extremely lite version): 我基本上建立了两个这样的表(精简版):

Table 1 : 表1

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

Table 2 : 表2

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

All the amount columns needed to be summed separately, the output to be similar to this: 所有数量列都需要单独求和,输出类似于以下内容:

Query results: 查询结果:

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

The joins I've tried result in the records duplicating (and summing) by a factor of the times the ID repeats in the second table. 我尝试的联接导致记录重复(和求和)记录是ID在第二张表中重复的次数的一部分。 I have no primary key to connect these tables. 我没有主键来连接这些表。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks! 谢谢!

To solve this problem correctly, you need to do the aggregations separately. 为了正确解决此问题,您需要单独进行聚合。 This will work even when both tables have multiple rows for the same id: 即使两个表都具有相同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

The above query gives the idea with a group by . 上面的查询给出了一个group by的想法。 Some people prefer a full outer join for this purpose: 为此,有些人希望使用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

The key is that the aggregations have to be done before any joins, so you don't have a problem of multiple rows. 关键是聚合必须任何联接之前完成,因此您不会有多行的问题。

On SQL Server 2005 or newer, you could use two CTE's (Common Table Expression) to do the summing/grouping per table, and then join the two - something like this: 在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

This gives me your desired output 这给了我你想要的输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM