2016-10-28 10 views
0

カラムbody = "Hey"のすべてのレコードを同じテーブルから取得する方法はありますか? "?しかし、同じdestが体になったたびに= "Hey"次の2つのレコードが同じdestに再び一致するようにこのレコードが必要です。SQL(PostgreSQL):同じキーに一致する次の2つのレコードと同じ値の行を選択します

パーティションは、同じdestとbody = "Hey"を持つ次の結果ペアに対してはリセットできません。

id | dest | body | received 
1 | A | Hey | 2016-10-28 01:00:00 
5 | B | Hey | 2016-10-28 02:00:00 
6 | B | X11 | 2016-10-28 03:00:00 
8 | A | Y11 | 2016-10-28 04:00:00 
11 | A | Y12 | 2016-10-28 05:00:00 
20 | C | Hey | 2016-10-28 06:00:00 
22 | A | Y13 | 2016-10-28 07:00:00 
25 | B | X12 | 2016-10-28 08:00:00 
26 | A | Hey | 2016-10-28 09:00:00 ! same "dest", if body = "Hey" we need it 
29 | A | Y22 | 2016-10-28 10:00:00 
33 | B | X13 | 2016-10-28 11:00:00 
35 | A | Y33 | 2016-10-28 12:00:00 

結果:次の2同じ `dest`レコードも` Hey`を持っているものhappense

1 | A | Hey | 2016-10-28 01:00:00 
8 | A | Y11 | 2016-10-28 04:00:00 
11 | A | Y12 | 2016-10-28 05:00:00 
5 | B | Hey | 2016-10-28 02:00:00 
6 | B | X11 | 2016-10-28 03:00:00 
20 | B | X12 | 2016-10-28 08:00:00 
20 | C | Hey | 2016-10-28 06:00:00 
26 | A | Hey | 2016-10-28 09:00:00 
29 | A | Y22 | 2016-10-28 10:00:00 
35 | A | Y33 | 2016-10-28 12:00:00 
... 
+0

? – Nikhil

+0

@Nikhil結果セットに表示する必要があります – nenad007

答えて

1
select id, dest, body, received 
from (
    select 
     *, 
     row_number() over (partition by dest, part) rn 
    from (
     select 
      *, 
      sum((body = 'Hey')::int) over (partition by dest order by id) part 
     from a_table 
     ) s 
    ) s 
where rn < 4 
order by dest, id; 

id | dest | body |  received  
----+------+------+--------------------- 
    1 | A | Hey | 2016-10-28 01:00:00 
    8 | A | Y11 | 2016-10-28 04:00:00 
11 | A | Y12 | 2016-10-28 05:00:00 
26 | A | Hey | 2016-10-28 09:00:00 
29 | A | Y22 | 2016-10-28 10:00:00 
35 | A | Y33 | 2016-10-28 12:00:00 
    5 | B | Hey | 2016-10-28 02:00:00 
    6 | B | X11 | 2016-10-28 03:00:00 
25 | B | X12 | 2016-10-28 08:00:00 
20 | C | Hey | 2016-10-28 06:00:00 
(10 rows) 
関連する問題