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

看板Database作者 (可愛小孩子)時間8年前 (2016/04/29 16:25), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串4/10 (看更多)
因線上 sqlfiddle.com 好像出了問題 所以將 sql 貼到板上: create table #t ( id int, year int, unit char(1) ) -- 建立測資 insert into #t select 1,99,'A' insert into #t select 1,98,'B' insert into #t select 1,97,'B' insert into #t select 1,96,'B' insert into #t select 2,99,'B' insert into #t select 2,98,'B' insert into #t select 2,97,'B' insert into #t select 3,97,'C' insert into #t select 3,96,'C' insert into #t select 3,95,'C' insert into #t select 3,94,'B' insert into #t select 4,97,'A' insert into #t select 4,96,'B' insert into #t select 4,95,'C' insert into #t select 4,94,'C' insert into #t select 4,93,'D' -- 解法 select distinct t1.* from #t t1 inner join #t t2 on t1.id = t2.id and ( (t1.year = t2.year + 1 and t1.unit != t2.unit) or (t1.year = t2.year - 1 and t1.unit != t2.unit) ) order by id,year desc 結果: id year unit 1 99 A 1 98 B 3 95 C 3 94 B 4 97 A 4 96 B 4 95 C 4 94 C 4 93 D ps. 紅色部份,不知道這樣顯示是不是你要的 ※ 引述《Schematic (小小寶的媽)》之銘言: : 資料庫名稱:SQL SERVER : 資料庫版本:2012 : 內容/問題描述: : 列出某位員工在哪一年換了單位,沒有換單位的員工不用列出 : Num id year unit : -------------------------- : 1 1 99 A : 2 1 98 B : 3 1 97 B : 4 1 96 B : 1 2 99 B : 2 2 98 B : 3 2 97 B : 1 3 97 C : 2 3 96 C : 3 3 95 C : 4 3 94 B : 1 4 97 A : 2 4 96 B : 3 4 95 B : 預期結果,員工1在99年從B單位換到A單位 : id year unit : ----------------------- : 1 99 A : 1 98 B : 3 95 C : 3 94 B : 4 97 A : 4 96 B : 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 210.61.233.210 ※ 文章網址: https://www.ptt.cc/bbs/Database/M.1461918301.A.3AC.html
文章代碼(AID): #1N8nfTEi (Database)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 4 之 10 篇):
文章代碼(AID): #1N8nfTEi (Database)