简体   繁体   English

SQL Server选择重复的行

[英]SQL Server select duplicated rows

I am newbie to SQL Server, and I want to select all those who changed their department at least once. 我是SQL Server的新手,我想选择所有至少一次更换部门的人员。

The table structure is: 表结构为:

  • BusinessEntityID BusinessEntityID
  • DepartmentID DepartmentID的
  • ShiftID ShiftID
  • StartDate 开始日期
  • RateChangeDate RateChangeDate
  • Rate
  • NationalIDNumber 身份证号码

I have the following code to generate an intermediate table 我有以下代码来生成中间表

select distinct 
   DepartmentID, NationalIDNumber
from 
   Table
where 
   NationalIDNumber in (select NationalIDNumber 
                        from Ben_VEmployee 
                        group by NationalIDNumber
                        having count(NationalIDNumber) > 1)

Output: 输出:

DepartmentID NationalIDNumber
-----------------------------
1               112457891
2               112457891
4                24756624
4               895209680
5                24756624
5               895209680
7               259388196

My questions is: how to remove non-duplicate records in the intermediate table as above? 我的问题是:如何删除上述中间表中的非重复记录?

So record "7 - 259388196" should be removed because he did not change department. 因此,应删除记录“ 7-259388196”,因为他没有更改部门。

Thanks. 谢谢。

Try using group by and comparing the maximum and minimum department. 尝试使用group by并比较最大和最小部门。 If it changed, then these will be different: 如果更改,则这些将有所不同:

select NationalIDNumber 
from Ben_VEmployee 
group by NationalIDNumber
having min(DepartmentID) <> max(DepartmentID);

If you need the actual departments, you can join this back in to the original data. 如果需要实际部门,可以将其重新加入原始数据。

If you want a list of every ID number that has been in more than one department, you can use 如果要列出一个以上部门中的每个ID号的列表,可以使用

SELECT COUNT(DepartmentID) AS noDepartments
, NationalIDNumber 
FROM Table
GROUP BY NationalIDNumber 
HAVING COUNT(DepartmentID) > 1

If you want to delete the records for the deparment the employee used to be in, but isn't any more, than you'd have to know which department that was to know which record to delete! 如果您想删除该员工曾经所在的部门的记录,但现在仅此而已,那么您将必须知道哪个部门知道要删除哪个记录! If you do know this, then say, and we can work it out. 如果您知道这一点,请说出来,我们可以解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM