我正在尝试查询与特定offer_id
相关联的消息对。
使用子查询:
WITH X AS (
SELECT M.offer_id
FROM quotes_site.messages M
where (regexp_substr (REPLACE(M.body, ' ', ''), '[0][0-9]{8,12}') != '') and (M.body NOT iLIKE '%agreement%' AND M.author_type = 'User') AND
M.created_at BETWEEN '2016-01-03' AND '2016-02-03'
)
然后通过将X与原始表连接,我得到与此id
相关联的主题(对于所有可用的author_type
)
SELECT MSG.body, MSG.offer_id, MSG.author_type
FROM quotes_site.messages MSG
INNER JOIN X
ON MSG.offer_id = X.offer_id
ORDER BY MSG.offer_id, MSG.created_at
问题是我如何让表MSG包含我在子查询中找到的消息,而且只包含按时间顺序排列在它之前的消息(但是对于同一个offer_id
)
答案 0 :(得分:0)
您可以将ROW_NUMBER
与PARTITION BY
子句一起使用,以便枚举属于同一offer_id
组的邮件:
WITH M AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY offer_id
ORDER BY created_at DESC) AS rn
FROM quotes_site.messages
) X AS (
SELECT M.offer_id, M.rn
FROM M
WHERE (regexp_substr (REPLACE(M.body, ' ', ''), '[0][0-9]{8,12}') != '')
AND (M.body NOT iLIKE '%agreement%' AND M.author_type = 'User')
AND (M.created_at BETWEEN '2016-01-03' AND '2016-02-03')
)
SELECT M.body, M.offer_id, M.author_type
FROM M
INNER JOIN X ON MSG.offer_id = X.offer_id AND M.rn BETWEEN X.rn AND x.rn - 1
ORDER BY M.offer_id, M.created_at