在SQL Server中将重复行连接到一行

时间:2014-07-24 12:26:09

标签: sql sql-server

id name number counter
1 test  010101 2
2 test  010101 1

我需要选择具有相同数字名称组合的重复行。我需要用两行中的计数器总和更新其中一行中的计数器,然后删除第二行

我正在使用以下查询来选择复制,但我无法进行更新:

SELECT *
FROM [prof]
WHERE ID NOT IN
  (
  SELECT MAX(ID)
  FROM [prof]
  GROUP BY number, name
  )

4 个答案:

答案 0 :(得分:1)

这将采用两个语句,最好包含在一个事务中:

update prof
set counter = (select SUM(counter) from prof group by number, name)
where ID in (select MAX(id) from prof group by number, name);

delete from prof where ID not in 
(select MAX(id) from prof group by number, name);

答案 1 :(得分:1)

这将更新计数器并保留第一个(最低)ID。它只会保留一个唯一的ID,所以如果有3行或更多行具有相同的名称,那么这仍然有效。

Update [prof]
set counter=a.cnt
from [prof] p inner join ( 
    select name,number,sum(counter)cnt
    from [prof] 
    group by name,number)a
on p.name=a.name and p.number=a.number;

delete [prof] 
from [prof] join (
     select id,row_number () over (partition by name, number order by id asc)row 
     from [prof])d 
on [prof].id=d.id
where d.row>1;

答案 2 :(得分:1)

这是一种使用cte的方法。这是cte的样子

id  name    number  counter totalCounter    DupNum
2   test1   10101         1            3         1
1   test1   10101         2            3         2
5   test2   10102         5           12         1
4   test2   10102         4           12         2
3   test2   10102         3           12         3

您可以使用已注释掉的delete语句运行整个事务来更新数据。然后注释掉更新语句并取消注释删除并再次运行。

;WITH table1_cte
AS
(
  SELECT id
    name, 
    number, 
    counter,
    ROW_NUMBER() over(PARTITION BY name, number ORDER BY id DESC) AS DupNum,
    SUM(counter) over (PARTITION BY name, number) AS totalCounter
  FROM prof
)

UPDATE table1_cte
SET counter = totalCounter
WHERE dupnum =1

--DELETE FROM table1_cte
--WHERE dupnum > 1

答案 3 :(得分:0)

更新将是这样的。

update prof
set counter = counterSum
from prof join
(select name, number, sum(counter) counterSum
from prof
where whatever
group by name, number) temp on prof.name = temp.name and prf.number = temp.number
where whatever

两个"无论什么" s应该是相同的。