如何在连续行中选择起始行的effdt?

时间:2016-05-17 12:08:16

标签: sql oracle

我有一份工作记录,其中有emplid,effdt和status。 现在我们有4种类型的状态,如A,L,P,S。

现在,如果我们有一个单一状态的连续行,那么我们必须从该状态开始的位置选择第一行的效果。

For Eg:
Emplid     Effdt    Status
100      4/4/2016    L
100     2/29/2016    L
100     12/25/2015   L
100     11/22/2015   A
100      9/22/2015   P

在上面的示例中,对于L状态,我需要选择行

Emplid   Effdt    Status
100    12/25/2015   L

先谢谢。

2 个答案:

答案 0 :(得分:1)

Oracle安装程序

CREATE TABLE table_name ( emplid, effdt, status ) AS
SELECT 100, DATE '2016-04-04', 'L' FROM DUAL UNION ALL
SELECT 100, DATE '2016-02-29', 'L' FROM DUAL UNION ALL
SELECT 100, DATE '2015-12-25', 'L' FROM DUAL UNION ALL
SELECT 100, DATE '2015-11-22', 'A' FROM DUAL UNION ALL
SELECT 100, DATE '2015-09-22', 'P' FROM DUAL;

<强>查询

SELECT *
FROM   (
  SELECT t.*,
         CASE status
              WHEN LAG( status ) OVER ( PARTITION BY emplid ORDER BY effdt )
              THEN 0
              ELSE 1
              END AS has_changed
  FROM   table_name t
)
WHERE  has_changed = 1;

<强>输出

EMPLID EFFDT      STATUS HAS_CHANGED
------ ---------- ------ -----------
   100 2015-09-22 P                1
   100 2015-11-22 A                1
   100 2015-12-25 L                1

答案 1 :(得分:0)

您可以使用“行数差异”技巧对这些进行分组,以便为​​每位员工获取一行,并按顺序获取状态:

select emplid, status, min(effdt), max(effdt)
from (select t.*,
             (row_number() over (partition by emplid order by effdt) -
              row_number() over (partition by emplid, status order by effdt)
             ) as grp
      from t
     ) t
group by emplid, status, grp;