检测行的列更改

问题描述 投票:1回答:2

首先,我确实搜索了类似的代码,但是没有找到合适的代码。

我想做的是显示每位员工的employee_type_id更改时的行,列出响应的<< employee_id,date fromlast date_to。 [员工ID。

我尝试使用partition by和lag函数进行分区,但未能解决此问题。感谢您的任何帮助。

我有这个:

employee_id Date_From Date_To EMPLOYEE_TYPE_ID ----------- ----------------------- ----------------------- ---------------- 11223344 2016-11-07 00:00:00.000 2016-12-11 00:00:00.000 1 11223344 2016-12-12 00:00:00.000 2016-12-31 00:00:00.000 1 11223344 2017-01-01 00:00:00.000 2017-04-28 00:00:00.000 38 11223344 2017-04-29 00:00:00.000 2017-06-30 00:00:00.000 38 11223344 2017-07-01 00:00:00.000 2017-11-30 00:00:00.000 1 11223344 2017-12-01 00:00:00.000 2018-01-04 00:00:00.000 38 ... 22233344 2012-06-01 00:00:00.000 2012-10-31 00:00:00.000 1 22233344 2012-11-01 00:00:00.000 2014-02-28 00:00:00.000 1 22233344 2017-12-01 00:00:00.000 2018-01-04 00:00:00.000 39 22233344 2018-01-05 00:00:00.000 2018-03-09 00:00:00.000 2

这就是我要实现的目标:

employee_id   Date_From              EMPLOYEE_TYPE_ID
----------- -----------------------  ----------------
11223344      2016-11-07 00:00:00.000 2016-12-31 00:00:00.000 1
11223344      2017-01-01 00:00:00.000 2017-06-30 00:00:00.000 38
11223344      2017-07-01 00:00:00.000 2017-11-30 00:00:00.000 1
11223344      2017-12-01 00:00:00.000 2018-01-04 00:00:00.000 38
...
22233344      2012-06-01 00:00:00.000 2014-02-28 00:00:00.000 1
22233344      2017-12-01 00:00:00.000 2018-01-04 00:00:00.000 39
22233344      2018-01-05 00:00:00.000 2018-03-09 00:00:00.000 2
sql sql-server tsql gaps-and-islands
2个回答
0
投票
这是使用窗口函数解决它的一种方法:

select employee_id, min(date_from) date_from, max(date_to) date_to, employee_type_id from ( select t.*, row_number() over(partition by employee_id order by date_from) rn1, row_number() over(partition by employee_id, employee_type_id order by date_from) rn2 from mytable t ) t group by employee_id, employee_type_id, rn1 - rn2

内部查询将记录划分为两个不同的分区(每个员工和每个员工

类型)。当行号之间的差异发生变化时,将启动一个新的孤岛(您可以独立运行子查询并查看其产生的结果)。然后,外部查询仅按组聚合。

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.