简体   繁体   中英

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.

The table structure is:

  • BusinessEntityID
  • DepartmentID
  • ShiftID
  • StartDate
  • 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.

Thanks.

Try using group by and comparing the maximum and minimum department. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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