I have a question about SQL Server.
Table: emp
empid | name |sal 1 | abc |100 2 | def |200 3 | test |300 2 | har |500 3 | jai |600 4 | kali |240
This table has duplicate data based on the table above. I want to remove duplicate data from emp table
And duplicate data should be loaded into the empduplicate table.
Here empid is unique. If empid displayed multiple times, then this entry is considered a duplicate.
Structure
empduplicate as follows:
Empid | name | sal
Finally, after deleting the duplicate data, I want the data in the emp table to look like this:
empid | name | sal 1 | abc | 100 4 | kali | 240
To remove duplicates, I tried this code:
;with duplicate as ( select *, row_number()over (partition by empid order by empid) as rn from emp ) delete from duplicate where rn > 1
But I can not delete entire entries.
Example: empid=2 has duplicate data
empid|name |sal 2 |def |200 2 |har |500
I need to delete integer empid=2 matching entries. empid=2 has a duplicate and needs to be removed from the emp table.
And the empduplicate table should load duplicate data:
empid | name |sal 2 |def |200 2 |har |500 3 |test |300 3 |jai |600
To enter duplicate data, I tried this code:
insert into empduplicate select id, name, sal from emp group by id having count(*) > 1
This request causes an error:
The column "duplicate.name" is not valid in the select list because it is not contained in the aggregate function or in the GROUP BY clause.
Please tell me how to write a query to complete my task in SQL Server