尝试通过offer_id检索第一行分区

时间:2016-02-22 11:37:52

标签: sql postgresql amazon-redshift window-functions

假设我有一个包含列的表

身体| offer_id | created_at

我需要通过offer_id对它们进行分组,按created_at进行排序,然后检索此表中的第一行。我现在使用以下逻辑

select first_value(M.body) over (partition by M.offer_id order by M.created_at ASC ROWS UNBOUNDED PRECEDING), 
        (select created_at 
         from quotes_site.offers O 
            where O.id = M.offer_id) as crt

from quotes_site.messages M
    where M.created_at between '2016-01-01' and '2016-02-01'

虽然没有错误,但查询无限期地运行,因此我认为必定存在错误。我对框架条款也不是很熟悉,因此非常感谢更详细的解释

P.S。服务器在AWS Redshift上运行

2 个答案:

答案 0 :(得分:2)

我建议使用row_number():

SELECT * FROM (
    SELECT t.offer_id,t.body,t.created_at,s.created_at,
           ROW_NUMBER() OVER(PARTITION BY t.offer_ID ORDER BY t.created_at) as rnk
    FROM quotes_site.messages t
    INNER JOIN quotes_site.offers s
    ON(s.id = t.offer_id))
WHERE rnk = 1

答案 1 :(得分:0)

如何使用distinct on代替:

select distinct on (M.offer_Id), M.*, o.created_at as o_created_at
from quotes_site.messages M left join
     quotes_site.offers O
     ON  O.id = M.offer_id
where M.created_at between '2016-01-01' and '2016-02-01'
order by M.offer_id, M.created_at;