PostgesSQL - 仅针对找到的最新范围选择行

时间:2018-04-17 21:31:06

标签: sql database postgresql database-design relational-database

我有这个选择陈述

  

SELECT id,likes,markers,search_body,remote_bare_jid,direction   FROM mam_message,其中user_id ='20'和remote_bare_jid =   '5a95c47078f92c6337019521'ORDDER BY id DESC;

返回以下内容

enter image description here  我想要检索最新范围方向'I'的行 - > 'I'

这:

SELECT id, liked, markers, search_body, remote_bare_jid, direction
 FROM mam_message 
 where user_id ='20' 
 AND remote_bare_jid = '5a95c47078f92c6337019521' 
 ORDER BY id DESC 
 limit 4;

enter image description here

即使范围不在顶部

enter image description here

我仍然只能获得最新的方向'我'

这(高端): enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用窗口函数direction找到转换行(其中lag().从O更改为I)将这些行标记为1(其他为0)。接下来,计算这些标记的累积总和。寻求的组将得到总和= 1.例如:

with example(id, direction) as (
values
    (1, 'O'),
    (2, 'I'),
    (3, 'I'),
    (4, 'I'),
    (5, 'O'),
    (6, 'I')
)

select id, direction
from (
    select id, direction, sum(mark) over w
    from (
        select 
            id, direction, 
            (lag(direction, 1, 'O') over w = 'O' and direction = 'I')::int mark
        from example
        window w as (order by id)
        ) s
    window w as (order by id)
    ) s
where direction = 'I' and sum = 1
order by id

 id | direction 
----+-----------
  2 | I
  3 | I
  4 | I
(3 rows)