I am using VS2005 C# and SQL Server 2005. I want to form an SQL query with the following condition:
Check for duplicated user in Table1 tb1 where tb1 has more than one [Emp.Name]
EDIT:
Simply saying, if I am only checking duplicate for [emp name], there’s no way I can select [employeeID]?
Because if I use
INSERT INTO DuplicateUserInTb1(EmployeeID, [Emp Name], Status, Issue)
SELECT tb1.EmployeeID, tb1.[Emp Name], 'Active', 'Duplicated user in Table1'
FROM Table1 tb1 GROUP BY tb1.[employeeID], tb1.[emp name] HAVING COUNT(tb1.[emp name]) >1
I will not be able to see any duplicated [emp name] rows inserted.
However, if I use
INSERT INTO DuplicateUserInTb1([Emp Name], Status, Issue)
SELECT tb1.EmployeeID, tb1.[Emp Name], 'Active', 'Duplicated user in Table1'
FROM Table1 tb1 GROUP BY tb1.[emp name] HAVING COUNT(tb1.[emp name]) >1
I am able to retrieve duplicated [emp name], however, without [employeeID].
EDITED:
Working on these 2 queries provided by Zohalib and Michal Powaga respectively:
INSERT INTO DuplicateUserInTb1(EmployeeID, [Emp Name], Status, Issue)
select t.emp_id, t.empname, t.active, t.du
from (select s1.emp_id, s1.empname,'Active' as active, 'Duplicate User' as du,
ROW_NUMBER() OVER (PARTITION BY s1.empName ORDER BY s1.empName) as rowNum
from table s1,
(select emp_name, count(*)
from table
group by emp_name
having count(*) > 1) s2
where s1.emp_name = s2.emp_name
) t where t.rowNum = 1
Error : No column was specified for column 2 of ‘s2
insert into DuplicateUserInTb1(EmployeeID, [Emp Name], Status, Issue)
select employeeID, [emp name], 'Active', 'Duplicated user in Table1'
from Table1 t1
join (
select [emp name]
from Table1
group by [emp name]
having count(*) > 1
) t on t1.[emp name] = t.[emp name]
Error: *Ambiguous column name '[Emp name]'
Would appreciate any help, thank you.
When you use Group By clause, then your select clause can only contain columns
Moreover, in your query, you are inserting values in three columns, but your select clause is selecting four values, should’nt this be a problem ?
try following query to insert duplicates based on empname