选择实习生同行历史Oracle

时间:2013-05-24 14:50:52

标签: oracle

我有一个带有empid,shiftdate和peerid的表T1。这可以存储员工培训某人的历史。例如,对于员工ABCD,这是我拥有的数据:

EMPLOYEE|SHIFT_DATE|PEERID  
ABCD 05/10/2013 A123  
ABCD 05/09/2013 A123  
ABCD 05/08/2013 A123  
ABCD 05/07/2013 X456  
ABCD 05/06/2013 X456  
ABCD 05/05/2013 X456  
ABCD 05/04/2013 A123  
ABCD 05/03/2013 A123  
ABCD 05/02/2013 A123  
ABCD 05/01/2013 A123  

我想选择员工,受训人员和受训人员(日期)。 从上面的数据可以看出,一些受训者可以在不同的非连续日期/期间块上重复,因此每个数据周期都需要作为一个单独的培训期来处理,如:

EMPLOYEE|TRAINED_SINCE|TRAINEE  
ABCD 05/08/2013 A123  
ABCD 05/05/2013 X456  
ABCD 05/01/2013 A123  

我该怎么做?请帮忙。

2 个答案:

答案 0 :(得分:1)

好吧......太晚了几秒钟:(

    select * from (
            select employee
              , decode(lag(peerid,1,'') over (partition by employee order by shift_date), peerid, null, shift_date)  trained_since
              , peerid
            from abe_trainee
    )
    where trained_since is not null

答案 1 :(得分:0)

使用LAG定义边界:

SQL> SELECT employee, shift_date, peer_id
  2         CASE
  3            WHEN peer_id = lag(peer_id)
  4                           over(PARTITION BY employee ORDER BY shift_date)
  5            THEN
  6             0
  7            ELSE
  8             1
  9         END gap
 10    FROM DATA;

EMPLOYEE     SHIFT_DATE  PEER_ID             GAP
------------ ----------- ------------ ----------
ABCD         01/05/2013  A123                  1
ABCD         02/05/2013  A123                  0
ABCD         03/05/2013  A123                  0
ABCD         04/05/2013  A123                  0
ABCD         05/05/2013  X456                  1
ABCD         06/05/2013  X456                  0
ABCD         07/05/2013  X456                  0
ABCD         08/05/2013  A123                  1
ABCD         09/05/2013  A123                  0
ABCD         10/05/2013  A123                  0

使用外部查询检索这些行:

SQL> SELECT employee, shift_date since, peer_id
  2    FROM (SELECT employee, shift_date, peer_id,
  3                 CASE
  4                    WHEN peer_id = lag(peer_id)
  5                                   over(PARTITION BY employee
  6                                        ORDER BY shift_date)
  7                    THEN
  8                     0
  9                    ELSE
 10                     1
 11                 END gap
 12         FROM DATA)
 13  WHERE gap = 1;

EMPLOYEE     SINCE       PEER_ID
------------ ----------- ------------
ABCD         01/05/2013  A123
ABCD         05/05/2013  X456
ABCD         08/05/2013  A123