如何将行数据添加到第一次出现的字符串字段

时间:2013-03-25 21:36:05

标签: sql

我找到了很多关于如何删除重复行的示例,但它们都涉及具有唯一整数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

感谢您的帮助。

EDIT 我正在使用MySQL

3 个答案:

答案 0 :(得分:3)

我认为只需一个简单的GROUP BYSUM()即可获得您正在寻找的结果:

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

See it in action with Sql Fiddle

答案 1 :(得分: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;

DEMO

答案 2 :(得分:0)

试试这个......

select stringID, sum(v1), sum(v2), sum(v3)
from yourtable
group by stringID