我有一个包含以下结构的表
sys_id(identity) | id | group_id | fld_id | val
-----------------------------------------------
我有一个查询
SELECT id,group_id,fld_id,val,COUNT(*)
FROM [DB_ALERT].[dbo].[DATATABLE]
GROUP BY id,group_id,fld_id,val
HAVING COUNT(*)>1
结果集是这样的
ID | group_id | fld_id | val| count(*)
__________________________________________
1000001| 1 | 1 | 23 | 2
1000003| 1 | 1 | 24 | 5
1000008| 1 | 1 | 14 | 4
现在在结果集中,我想为每条记录仅取前1个sys_id,并删除具有相同ID,Group,Fld和val的其他记录(删除其公开内容)。我知道如何使用游标执行此操作,但有没有办法在单个查询中执行此类操作?
答案 0 :(得分:4)
请尝试:
;with c as
(
select *, row_number() over(partition by ID, Group, Fld, val order by ID, Group, Fld, val) as n
from YouTable
)
delete from c
where n > 1