Sql server 合并单个SQL表中的行
我有一张桌子,上面有像这样的行Sql server 合并单个SQL表中的行,sql-server,merge,Sql Server,Merge,我有一张桌子,上面有像这样的行 ID | Key | Value1 | Value2 | Type 55 | 012018| 0 | 0 | 1 55 | 012018| 50 | 10 | 1 我需要更新此表以删除这些重复项,以便我的ID、键和类型匹配,并且添加了值1和值2 结果 ID | Key | Value1 | Value2 | Type 55 | 012018| 50 | 10 | 1 我认为您只
ID | Key | Value1 | Value2 | Type
55 | 012018| 0 | 0 | 1
55 | 012018| 50 | 10 | 1
我需要更新此表以删除这些重复项,以便我的ID、键和类型匹配,并且添加了值1和值2
结果
ID | Key | Value1 | Value2 | Type
55 | 012018| 50 | 10 | 1
我认为您只需要按ID、键和类型对它们进行分组
SELECT ID, Key, SUM(Value1) AS Value1, SUM(Value2) AS Value2, Type
FROM TABLE
GROUP BY ID, Key, Type
您可以使用临时表存储计算值,通过连接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
请注意,我在一个表中有许多ID、键和类型。例如115022018,20,20,1和115022018,30,30,1。Value1和Value2始终是数字。是否只有2个条目或多个条目。如果是多个,那么逻辑是什么?可以有2个或更多。我试着使用爱慕者的答案,不管有多少重复,它都是正确的