如何合并两行并在UPDATE中汇总一些列?

时间:2014-07-02 12:23:23

标签: sql-server tsql merge sql-update

我使用SQL Server并且只有在两个特定列(我的示例中为Col_01和Col_02)中它们之间具有相同值时才需要合并多个行。 当我合并它们时,我必须总结一些列(在我的示例中为Col_03和Col_04)。

我认为一个例子会更明确。这是我简化的表格:

| ID  | Col_01 | Col_02 | Col_03 | Col_04  |
| 1   | ABC    | DEF    | 2      | 2       | 
| 2   | ABC    | DEF    | 1      | 0       | 
| 3   | DEF    | GHI    | 0      | 2       | 
| 4   | ABC    | GHI    | 1      | 0       | 
| 5   | JKL    | GHI    | 0      | 2       | 

这是我更新后的所需内容:

| ID  | Col_01 | Col_02 | Col_03 | Col_04  | 
| 2   | ABC    | DEF    | 3      | 2       | 
| 3   | DEF    | GHI    | 0      | 2       | 
| 4   | ABC    | GHI    | 1      | 0       | 
| 5   | JKL    | GHI    | 0      | 2       | 

我合并了ID 1和ID 2,因为它们具有相同的Col_01和相同的Col_02。

我尝试过像这样的查询

SELECT MAX(ID), Col_01, Col_02, SUM(Col_03), SUM(Col_04)
FROM Table
GROUP BY Col_01, Col_02

我已经获得了合并的行,但是我放弃了未合并的行。

我不知道如何在UPDATE查询中正确使用它,以便将行与相同的行合并(Col_01,Col_02)并保留其他行。你能帮我这么做吗?

2 个答案:

答案 0 :(得分:2)

试试这个:

UPDATE  T SET 
        T.Col_03 = G.Col_03,
        T.Col_04 = G.Col_04
FROM    Table AS T INNER JOIN
        (SELECT   MAX(ID) AS ID, Col_01, Col_02, SUM(Col_03) AS Col_03, SUM(Col_04) AS Col_04
         FROM     Table
         GROUP BY Col_01, Col_02) AS G 
         ON G.ID = T.ID

答案 1 :(得分:2)

所以你实际上需要从原始表中删除一些行。请使用MERGE语句:

MERGE Table tgt
USING (SELECT MAX(ID) as ID, Col_01, Col_02, SUM(Col_03) AS Col_03, SUM(Col_04) AS Col_04
       FROM Table
       GROUP BY Col_01, Col_02) src ON tgt.ID = srs.ID
WHEN MATCHED THEN
    UPDATE
    SET Col_03 = src.Col_03, Col_04 = src.Col_04
WHEN NOT MATCHED BY SOURCE THEN
    DELETE