我有一个关于 SQL Server 的问题。
表:emp
empid | name |sal
1 | abc |100
2 | def |200
3 | test |300
2 | har |500
3 | jai |600
4 | kali |240
此表包含基于上表的重复数据我想从 emp
表中删除重复数据
并且重复的数据应该加载到empduplicate
表中。
这里 empid
是唯一的。如果 empid
显示多次,则该记录被视为重复。
empduplicate
结构如下所示:
Empid | name | sal
最后删除重复数据后,我希望看到 emp
表中的数据如下所示:
empid | name | sal
1 | abc | 100
4 | kali | 240
为了删除重复项,我尝试了以下代码:
;with duplicate as
(
select
*,
row_number()over (partition by empid order by empid) as rn
from emp
)
delete from duplicate
where rn > 1
但我无法删除整个记录。
示例:empid=2
有重复数据
empid|name |sal
2 |def |200
2 |har |500
我需要删除整个 empid=2
相应记录。 empid=2
重复,需要从 emp
表中删除。
并且empduplicate
表需要加载重复数据,如下所示:
empid | name |sal
2 |def |200
2 |har |500
3 |test |300
3 |jai |600
为了插入重复数据,我尝试了以下代码:
insert into empduplicate
select
id, name, sal
from
emp
group by
id
having
count(*) > 1
该查询抛出错误:
Column 'duplicate.name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
请告诉我如何编写查询来在 SQL Server 中完成我的任务
最佳答案
你就快到了。不要使用 ROW_NUMBER
,而是使用 COUNT
:
WITH CteInsert AS(
SELECT *,
cnt = COUNT(empid) OVER(PARTITION BY empid)
FROM emp
)
INSERT INTO empduplicate(empid, name, sal)
SELECT
empid, name, sal
FROM CteInsert
WHERE cnt > 1;
WITH CteDelete AS(
SELECT *,
cnt = COUNT(empid) OVER(PARTITION BY empid)
FROM emp
)
DELETE FROM CteDelete WHERE cnt > 1;
您需要先执行INSERT
,然后再执行DELETE
。此外,您可能希望将其包含在单个事务中。
关于sql-server - 删除重复数据并加载到 SQL Server 中的另一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34427974/