在PostgreSQL上分组

时间:2013-11-06 03:01:17

标签: sql postgresql group-by

我有一个应用程序表,每个应用程序都可以有活动,每次更新活动时都会在activityupdate表中有一个日志。

activityupdate表: - ID - activity_id - 用户身份 - 日期

活动表: - ID - application_id - 排名 - ......

我想按活动排名

获取应用程序订单的所有活动的最后一次活动更新

我有

SELECT au
FROM activityupdate au
INNER JOIN activity ac
ON au.activity_id = ac.id
INNER JOIN application ap
ON ac.application_id = ap.id
WHERE ap.id = 3
GROUP BY au, ac.rank
ORDER BY ac.rank ASC

但这不起作用,我不知道为什么我必须在GROUP BY中设置au和ac.rank

感谢您的帮助

编辑, 谢谢戈登,我找到了解决方案

select *
from (SELECT au,
      row_number() over (partition by au.activity_id order by au.date desc) as seqnum
      FROM activityupdate au INNER JOIN
      activity ac
      ON au.activity_id = ac.id INNER JOIN
      application ap
      ON ac.application_id = ap.id
  WHERE ap.id = 3
  ORDER BY ac.rank ASC
 ) t
where seqnum = 1

1 个答案:

答案 0 :(得分:2)

您不需要聚合。函数row_number()可以满足您的需求。它为组内的行分配一个序号(由partition by子句定义)。数字的顺序由order by确定。

然后,您可以使用where子句选择最新的:

select *
from (SELECT au,
             row_number() over (partition by au order by rank desc) as seqnum
      FROM activityupdate au INNER JOIN
           activity ac
           ON au.activity_id = ac.id INNER JOIN
           application ap
           ON ac.application_id = ap.id
      WHERE ap.id = 3
     ) t
where seqnum = 1