1

我发现了许多如何删除重复行的示例,但它们都涉及具有唯一整数 id 的行。

这是我需要知道的。我想将所有重复的 stringID 合并在一起并对其他列的值求和。

我有这个:

stringID | v1 | v2 | v3
    a    | 2  |  3 | 4
    b    | 5  |  4 | 1
    a    | 1  |  1 | 2
    b    | 2  |  1 | 1

我要这个:

stringID | v1 | v2 | v3
    a    | 3  |  4 | 6
    b    | 7  |  5 | 2

感谢您的帮助。

编辑我正在使用 MySQL

4

3 回答 3

3

我认为只是一个简单的GROUP BYSUM()应该给你你正在寻找的结果:

SELECT
  StringID,
  SUM(v1) AS v1,
  SUM(v2) AS v2,
  SUM(v3) AS v3
FROM YourTable
GROUP BY StringID

使用 Sql Fiddle 查看它的实际效果

于 2013-03-25T21:41:47.460 回答
1

(免责声明:使用 SQL-Server >= 2005)

所以你想先更新所有记录的总和,然后你想删除重复:

更新:

WITH CTE AS
(
    SELECT stringID, 
           v1_sum = SUM(v1) OVER (PARTITION BY stringID),
           v2_sum = SUM(v2) OVER (PARTITION BY stringID),
           v3_sum = SUM(v3) OVER (PARTITION BY stringID),
           RN = ROW_NUMBER()OVER(PARTITION BY stringId Order By stringId)
    FROM dbo.TableName
)
UPDATE tn SET v1 = v1_sum, v2 = v2_sum, v3 = v3_sum
FROM CTE c 
INNER JOIN dbo.TableName tn ON c.stringId=tn.stringId
WHERE c.RN = 1;

删除:

WITH CTE AS
(
    SELECT 
        RN = ROW_NUMBER()OVER(PARTITION BY stringId Order By stringId)
    FROM dbo.TableName
)
DELETE FROM CTE WHERE RN > 1;

演示

于 2013-03-25T21:43:47.713 回答
0

尝试这个...

select stringID, sum(v1), sum(v2), sum(v3)
from yourtable
group by stringID
于 2013-03-25T21:42:11.667 回答