作者konkonchou (卡卡猫)
看板Database
标题Re: [SQL ] 列出一个栏位中开始变化的前後值
时间Wed May 4 02:46:30 2016
把两种换部门条件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://webptt.com/cn.aspx?n=bbs/Database/M.1462301192.A.801.html