如何从员工表中提取具有“名字,姓氏和出生日期”的员工

时间:2012-08-27 13:40:26

标签: tsql

我需要提取其姓氏,姓氏和出生日期相同的记录。 请找到以下示例。

Employeeid   firstname lastname DOB
00010         ravi      sagi     22/01/1990
00035         ravi      sagi     22/01/1990
00060         vasanth   guptha   20/01/1987
00115         vasanth   guptha   20/01/1987

你能帮忙写一下这个问题。

2 个答案:

答案 0 :(得分:4)

试试这个:

select *
from
  (
    select *,
           count(*) over(partition by firstname, lastname, DOB) as CC
    from YourTable
  ) as T
where T.CC > 1

答案 1 :(得分:1)

您可以JOIN自己比较firstnamelastnameDOB,以确保它们是相同的值然后employeeid是不一样的:

select * 
from yourtable t1
inner join yourtable t2
  on t1.firstname = t2.firstname
  and t1.lastname = t2.lastname
  and t1.dob = t2.dob
  and t1.empid != t2.empid

上述查询可能会显示重复记录,因此您可以使用以下内容(请参阅SQL Fiddle with Demo):

select DISTINCT t1.empid,
  t1.firstname,
  t1.lastname,
  t1.DOB
from yourtable t1
inner join yourtable t2
  on t1.firstname = t2.firstname
  and t1.lastname = t2.lastname
  and t1.dob = t2.dob
  and t1.empid != t2.empid

或者您可以使用EXISTS(请参阅SQL Fiddle with Demo):

select t1.empid,
  t1.firstname,
  t1.lastname,
  t1.DOB
from yourtable t1
where exists (SELECT *
              FROM yourtable t2
              WHERE t1.firstname = t2.firstname
                and t1.lastname = t2.lastname
                and t1.dob = t2.dob
                and t1.empid != t2.empid)