0

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

活动更新表: - id - activity_id - user_id - 日期

活动表:- id - application_id - rank - ...

我想按活动排名获取应用程序订单的所有活动的最后一个活动更新

我有

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
4

1 回答 1

2

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

然后,您可以选择最近的 usingwhere子句:

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
于 2013-11-06T03:05:00.247 回答