【问题标题】:Merge rows in single SQL table合并单个 SQL 表中的行
【发布时间】:2019-01-13 05:25:12
【问题描述】:

我有一张桌子,上面有类似

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

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

得到结果

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

【问题讨论】:

  • 请注意 - 我在一个表中有许多 ID、密钥和类型。例如115,022018,20,20,1 和 115,022018,30,30,1。并且 Value1 和 Value2 始终是数字。
  • 只有 2 个条目还是多个条目。如果是多个,那么逻辑是什么?
  • 可以有 2 个或更多。我尝试使用 Admir 的答案,无论有多少重复,它都能正常工作

标签: sql-server merge


【解决方案1】:

我认为您只想按 ID、密钥、类型对它们进行分组

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

【讨论】:

    【解决方案2】:

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

    注意:我已将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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      相关资源
      最近更新 更多