我有这个选择陈述
SELECT id,likes,markers,search_body,remote_bare_jid,direction FROM mam_message,其中user_id ='20'和remote_bare_jid = '5a95c47078f92c6337019521'ORDDER BY id DESC;
返回以下内容
这:
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;
即使范围不在顶部
我仍然只能获得最新的方向'我'
答案 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)