2015-05-06 37 views
0

我們有表是這樣的:SQL - 找到連續兩行相同的ID

ID PERSON GROUP ASSIGNEDGROUP CHANGEDATE 
1 null GROUP1 GROUP1   01.01.2014 
1 NAME1 null GROUP1   02.01.2014 
1 null GROUP2 GROUP2   03.01.2014 
2 null GROUP1 GROUP1   04.01.2014 
2 NAME1 null GROUP1   05.01.2014 
2 null GROUP2 GROUP2   06.01.2014 
2 null GROUP3 GROUP3   07.01.2014 

我們想找個連續兩行,其中PERSON領域將有相同ID null值,並根據日期領域。 (如果傷者場爲null,則GROUP字段的值,反之亦然)

所以在這個例子中只有最後兩行應列出,因爲它們是同一個ID和他們之間的日期是連續

2 null GROUP2 GROUP2   06.01.2014 
2 null GROUP3 GROUP3   07.01.2014 

我正在嘗試編寫一些SQL語法,但實際上並不知道如何開始,這可能是一些複雜的表達式。我想首先要做的是根據日期獲取兩個連續的行並檢查PERSON是否爲空。

預先感謝您

+0

關於CHANGEDATE字段,但對於相同的ID – Dejan

+0

如果連續三個日期? – jarlh

+0

嗨jarlh將不會有三個連續的日期,我們沒有這樣的例子在我們的表 – Dejan

回答

1

這是使用的好地方lag()lead()

select t.* 
from (select t.*, 
      lag(person) over (partition by id order by changedate) as person_prev, 
      lead(person) over (partition by id order by changedate) as person_next 
     from table t 
    ) t 
where person is null and 
     (person_prev is null or person_next is null); 

編輯:

以上不相當的工作,因爲NULL將是返回每個id的第一行或最後一行。糟糕!這裏是一個修復:

select t.* 
from (select t.*, 
      lag(person) over (partition by id order by changedate) as person_prev, 
      lead(person) over (partition by id order by changedate) as person_next, 
      lag(id) over (partition by id order by changedate) as id_prev, 
      lead(id) over (partition by id order by changedate) as id_next 
     from table t 
    ) t 
where person is null and 
     ((person_prev is null and id_prev is not null) or 
     (person_next is null and id_next is not null) 
    ); 

編輯II;

如何尋找兩個非空的組?

select t.* 
from (select t.*, 
      lag(group) over (partition by id order by changedate) as group_prev, 
      lead(group) over (partition by id order by changedate) as group_next 
     from table t 
    ) t 
where group is not null and 
     (group_prev is not null or group_next is not null); 

注意:group是一個非常糟糕的名稱,因爲它是一個SQL保留字。

+0

嗨Gordon這個工作但不完全。這是表格中一個ID的結果:8403 null NOC NOC 2015-05-05 15:05 8403 null NOC NOC 2015-05-05 15:40 – Dejan

+0

但實際數據爲:8403 null NOC NOC 2015-05-05 15: 05 8403 OZREN null NOC 15:12 8403 null SP SP 15:13 8403 DEJAN null SP 15:14 8403 null NOC NOC 15:40 – Dejan

+0

所以你會看到它返回2行但它們不是連續的 – Dejan