合并单个SQL表中的行

时间:2019-01-13 05:25:13

标签: sql-server merge

我有一张桌子,上面有

ID | Key   | Value1 | Value2 | Type  
55 | 012018| 0      | 0      |  1   
55 | 012018| 50     | 10     | 1  

我需要更新此表以删除这些重复项,以便我的 ID,密钥和类型 匹配,并且添加了Value1和Value2

获取结果

ID | Key   | Value1 | Value2 | Type  
55 | 012018| 50     | 10     |  1 

2 个答案:

答案 0 :(得分:1)

我想您只是想按ID,密钥,类型对它们进行分组

SELECT ID, Key, SUM(Value1) AS Value1, SUM(Value2) AS Value2, Type
FROM TABLE
GROUP BY ID, Key, Type

答案 1 :(得分:0)

您可以使用临时表存储计算出的值,通过加入Id,键,类型并重新插入来将其从表中删除。这样,您将在表中获得不同的值并删除重复项。我已经提供了示例,说明了如何做到这一点。

注意:我已将sql代码放入事务中并注释了提交部分,因此您可以轻松对其进行测试。

BEGIN TRAN PrototypeExample

-- create temp table where we will store calculated data
CREATE TABLE #tempValues(
    Id INT,
    [Key] INT,
    [Type] INT,
    Value1 INT,
    Value2 INT
)

-- insert calculated values into temp table
INSERT INTO 
    #tempValues
    (
        Id, 
        [Key], 
        [Type], 
        Value1, 
        Value2
    )
SELECT 
    e.Id, 
    e.[Key], 
    e.[Type], 
    SUM(e.Value1) Value1, 
    SUM(e.Value2) Value2
FROM 
    example e
GROUP BY 
    e.Id,
    e.[Key],
    e.[Type]

-- show data
SELECT * FROM #tempValues

-- delete data from my table 
DELETE 
    e 
FROM 
    example e
INNER JOIN 
    #tempValues t 
    ON 
        e.Id = t.Id 
        AND 
        e.[Key] = t.[Key] 
        AND 
        e.[Type] = t.[Type];

-- insert data from temp table
INSERT INTO
    example
    (
        Id, 
        [Key], 
        [Type], 
        Value1, 
        Value2
    )
SELECT
    t.Id,
    t.[Key],
    t.[Type],
    t.Value1,
    t.Value2
FROM
    #tempValues t

-- new data populated
SELECT * FROM example

-- delete temp table
IF OBJECT_ID('tempdb..#tempValues') IS NOT NULL DROP TABLE #tempValues

-- for testing
ROLLBACK TRANSACTION PrototypeExample

-- if you find it useful, commit
-- COMMIT TRANSACTION