按多个列不同的postrges上的id desc排序

时间:2016-09-14 14:15:14

标签: sql postgresql greatest-n-per-group distinct-on

SELECT impressions.* 
FROM impressions 
WHERE impressions.user_id = 2 
  AND impressions.action_name = 'show' 
  AND (impressions.message IS NOT NULL) 
GROUP BY impressionable_id, impressionable_type

我想从表中选择所有最后一次展示,这些展示在impressionable_id和impresssionable_type排序中是唯一的,通过降序ID并获得最后10个

进一步解释

id, impressionabale_type, impressionable_id, action_name

50012, assignment, 2, show
50011, assignment, 1, show
50010, person, 1, show
50009, assignment, 1, show
50008, person, 5, show
50007, person, 4, show
50006, person, 3, show
50005, person, 1, show
50004, person, 1, show
50003, person, 2, show
50002, person, 2, show
50001, person, 1, show
50000, person, 1, show

理想情况下我想要这个

50012, assignment, 2, show
50011, assignment, 1, show
50010, person, 1, show
50008, person, 5, show
50007, person, 4, show
50006, person, 3, show
50003, person, 2, show

我尝试过不同的分组,但我的sql知识充其量只是公平的。

我得到了

PG::GroupingError: ERROR:  column "impressions.id" must appear in the GROUP BY clause or be used in an aggregate function

请有人解决一些问题

2 个答案:

答案 0 :(得分:1)

也许这将满足您的需求:

SELECT t2.*
FROM (
    SELECT DISTINCT impressionable_id, impressionabale_type
    FROM impressions
    WHERE impressions.action_name = 'show'
) t1, LATERAL (
    SELECT *
    FROM impressions
    WHERE (t1.impressionable_id,t1.impressionabale_type) = (impressionable_id,impressionabale_type)
    ORDER BY id DESC
    LIMIT 1
) t2
ORDER BY id DESC
LIMIT 10

这将找到impressionable_idimpressionable_type的所有唯一组合,并且每个组合都会在id子查询中找到具有最大LATERAL的行。

答案 1 :(得分:0)

select *
from (
    select *,
        row_number() over (
            partition by impressionable_id, impressionable_type
            order by id desc
        ) as rn
    from impressions 
    where
        user_id = 2 
        and action_name = 'show' 
        and message is not null
) s
where rn = 1