2015-10-28 24 views
-7

需要員工詳細誰只有一個就業需要員工詳細誰只有一個就業

例如這是表

 
ID Name StartDate EndDate 
1 Fischel 01-May-97 Jan-99 
1 Fischel 08-May-92 02-Feb-99 
1 Fischel 11-May-92 04-May-10 
2 David 10-aug-1980 05-May-1981 
3 John 12-sep-1988  06-June-2009 
3 John 23-Aug-92 01-Nov-11 

輸出這樣

 
2 David 10-aug-1980 05-May-1981 
+1

關係數據庫管理系統使用的是哪個?? –

+3

請付出努力... –

+0

使用group by子where group with count = 1 –

回答

0
Select * from 
    (select *,row_number() over (partition by id order by StartDate desc) as rnm 
    from your table 
    )Derived_Table 
    where Derived_Table.rnm=1; 

OR

select * from table where id in (
select id 
from table group by id having count(*) =1) z; 
+0

@Patrick ..agree跟你一樣,但是所有的標準oracle,sql server teradata都支持它......而我工作其中之一。所以它是自發的反應... –

+0

第二個查詢有一個子選擇試圖返回兩列,但只與一列比較...從選擇列表中刪除計數(*)。 – jarlh

+0

@ jarlh..thanks for pointing .. :) –

0

使用NOT EXISTS返回用戶,如果相同的用戶名沒有任何其他日期。

select ID, Name, StartDate, EndDate 
from tablename t1 
where not exists (select 1 from tablename t2 
        where t2.id = t1.id 
        and (t2.StartDate <> t1.StartDate 
         or t2.EndDate <> t1.EndDate)) 

或者,有一個子查詢返回的所有ID只有一次出現:

select ID, Name, StartDate, EndDate 
from tablename t1 
where id in (select id from tablename 
      group by id 
      having count(*) = 1) 
相關問題