SQL检查表中的重复用户名

时间:2011-12-09 05:38:16

标签: c# sql sql-server sql-server-2005

我正在使用VS2005 C#和SQL Server 2005.我想形成一个具有以下条件的SQL查询:

检查 Table1 tb1 中的重复用户,其中 tb1 有多个[Emp.Name]

修改

简单地说,如果我只检查[emp name]的副本,我就无法选择[employeeID]

因为如果我使用

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 

我将无法看到插入任何重复的[emp name]行。

但是,如果我使用

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

但是,我可以检索重复的[emp name],但没有[employeeID]


编辑:

分别处理 Zohalib Michal Powaga 提供的这两个查询:

 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

错误:没有为's2

的第2列指定列
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]

错误:* Ambiguous column name '[Emp name]'


感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:2)

使用Group By子句时,select子句只能包含列

  

在分组

中提及      

或聚合函数,例如Count,SUM e.t.c   http://www.w3schools.com/sql/sql_groupby.asp

此外,在您的查询中,您要在三列中插入值,但是您的select子句正在选择四个值,这不是一个问题吗?

尝试按照查询插入基于empname

的重复项
    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(*) as counts
 from table 
 group by emp_name
 having count(*) > 1) s2
 where s1.emp_name = s2.emp_name 
) t where t.rowNum = 1

答案 1 :(得分:1)

insert into DuplicateUserInTb1(EmployeeID, [Emp Name], Status, Issue)
select t1.employeeID, t1.[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]