Re: [SQL ] 列出一個欄位中開始變化的前後值

作者: konkonchou (卡卡貓)   2016-05-04 02:46:30
把兩種換部門條件union應該就會是結果了
Select * from table1 t1 where exists (Select 1 from Table1 t2 where
t1.id=t2.id and t1.unit <> t2.unit and t1.year>t2.year)
and not exists (Select 1 from Table1 t3 where t1.id=t3.id and t1.unit=
t3.unit and t1.year>t3.year)
union
Select * from table1 t1 where exists (Select 1 from Table1 t2 where
t1.id=t2.id and t1.unit <> t2.unit and t1.year<t2.year)
and not exists (Select 1 from Table1 t3 where t1.id=t3.id and t1.unit=
t3.unit and t1.year<t3.year)
order by t1.id
結果
num id year unit
1 1 99 A
2 1 98 B
3 3 95 C
4 3 94 B
1 4 97 A
2 4 96 B
※ 引述《Schematic (小小寶的媽)》之銘言:
: 謝謝您的建議
: 因為後續還需要分析這些員工更換單位的原因
: 也就是還要跟其他tables交叉比對
: 我必須先把有更換單位的員工先挑出來
: 再來還要統計大家最喜歡轉入的單位為何
: 所以才想用這樣的呈現方式喔
: ※ 引述《popcorny (畢業了..@@")》之銘言:
: : 你的預期結果其實不容易實現,
: : 如果換個題目呢?
: : 呈現員工各個單位的在職年度區間
: : select
: : id,
: : unit,
: : min(year) as fromYear,
: : max(year) as toYear
: : from Emp
: : group by id, unit
: : order by id, fromYear;
: : 輸出
: : ID Unit fromYear toYeader
: :

Links booklink

Contact Us: admin [ a t ] ucptt.com