作者cutekid (可爱小孩子)
看板Database
标题Re: [SQL ] 列出一个栏位中开始变化的前後值
时间Fri Apr 29 16:24:58 2016
因线上 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://webptt.com/cn.aspx?n=bbs/Database/M.1461918301.A.3AC.html