2016-10-28 89 views
0

有沒有辦法從一個表中獲得每個記錄的列身體=「嘿」與下兩個記錄誰擁有相同的「dest 「?但是,每當同一個目標在body =「嘿」中得到時,我需要這條記錄,而後面的兩條記錄再次匹配相同的目標。SQL(PostgreSQL):選擇Rows等於下列兩個記錄匹配相同的密鑰

一個分區不幫我,因爲我不能「重置」它的下一對結果誰擁有相同的目標和身體=「嘿」。

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 

結果:

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

在未來2相同的'dest'記錄也有什麼happense'Hey'? – 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) 
相關問題