看板 Database 關於我們 聯絡資訊
把兩種換部門條件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 : : -------------------------- : : 1 B 96 98 : : 1 A 99 99 : : 2 B 97 99 : : 3 B 94 94 : : 3 C 95 97 : : 4 B 95 96 : : 4 A 97 97 : : 這樣可以看出員工1 : : B單位 96-98 : : A單位 99-99 : : 個人認為這樣也比較好處理 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.166.198.109 ※ 文章網址: https://www.ptt.cc/bbs/Database/M.1462301192.A.801.html