作者rockchangnew (rock)
看板Database
标题Re: [SQL ] 列出一个栏位中开始变化的前後值
时间Thu Apr 28 23:40:34 2016
※ 引述《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
: 谢谢
写得不是很好,请将就一下
with tmp as(select
ROW_NUMBER() over(partition by id,units order by tyear desc) as Num
,id
,tyear
,units
from [dbo].[Table_1])
,tmp2 as(select id from tmp where Num=1 group by id having count(id)>1)
select a.id,tyear,units from tmp a inner join tmp2 b on a.id=b.id
where Num=1 order by id,tyear desc
--
Sent from my Windows
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 1.34.194.8
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Database/M.1461858036.A.268.html