如何删除重复数据并在sql上求和它的值?

时间:2016-05-19 08:58:17

标签: sql sql-server tsql sql-delete

假设我有一个名为“records”的数据库表,它有三个实体“id”,“name”,“score”。

如果有重复的值,如;

id  name  score
1   ben   10
2   adam   4
3   sarah  2
4   ben    5
5   mark   3

由于有两个benı可以使用此sql语句删除其中一个

DELETE FROM records
WHERE id IN
( SELECT MAX(id) FROM records
GROUP BY name
HAVING COUNT(*) > 1)

但是我怎样才能将ben的值加到其他ben上并得到类似的东西;

id  name  score
1   ben    15
2   adam   4
3   sarah  2
5   mark   3

4 个答案:

答案 0 :(得分:0)

SELECT Min(id) as id ,name,SUM(score) as score FROM records
GROUP BY name

答案 1 :(得分:0)

尝试以下查询:

select id,name,sum(score) over (partition by name) score
into #t1
from test3
order by id

DELETE FROM #t1
WHERE id IN
(SELECT MAX(id) FROM #t1
GROUP BY name
HAVING COUNT(*) > 1)

select * from #t1
order by id

drop table #t1

答案 2 :(得分:0)

您可以使用:

-- get min(id) and total
SELECT id = MIN(id),name, total = SUM(score)
INTO #temp
FROM records
GROUP BY name;

-- update score
UPDATE r
SET score = total
FROM records r
JOIN #temp t
  ON r.name = t.name;

-- delete redundant rows
DELETE r
FROM records r
LEFT JOIN #temp t
 ON r.id = t.id
WHERE t.id IS NULL;

SELECT * FROM records;

LiveDemo

使用MERGE

MERGE records AS tgt
USING (SELECT id = MIN(id),name, total = SUM(score)
       FROM records
       GROUP BY name) AS src
 ON tgt.name = src.name
WHEN MATCHED AND tgt.id <> src.id THEN
  DELETE
WHEN MATCHED THEN
  UPDATE SET score = total;

LiveDemo2

输出:

╔════╦═══════╦═══════╗
║ id ║ name  ║ score ║
╠════╬═══════╬═══════╣
║  1 ║ ben   ║    15 ║
║  2 ║ adam  ║     4 ║
║  3 ║ sarah ║     2 ║
║  5 ║ mark  ║     3 ║
╚════╩═══════╩═══════╝

答案 3 :(得分:0)

使用此查询:

--This will delete all duplicate records except their first occurrence. You may ignore this part if you do not need to delete
DELETE FROM T 
WHERE Id IN (
             SELECT Id FROM(
                            --This select will produce the result that you are looking for
                            SELECT Id, 
                                   name, 
                                   SUM(Score)OVER(PARTITION BY name) AS S,
                                   ROW_NUMBER()OVER(PARTITION BY name ORDER BY Id ) AS RN
                            FROM T
                           ) AS K WHERE RN>1
             )