Sql获得每种类型的顶行

时间:2011-10-06 13:26:36

标签: sql db2

我有一张表WorkLog(personId number, actionType number, doneOn timeStamp),现在我怎样才能为每个人提供最近的动作。

数据就像

p1 a1 timestamp1
p1 a2 timestamp2
p2 a1 timestamp3
p2 a3 timestamp4
p3 a1 timestamp5

输出应为

p1 a2 timestamp2
p2 a1 timestamp3
p3 a1 timestamp5

数据库是DB2

1 个答案:

答案 0 :(得分:6)

这是“每组最大的n”查询。根据{{​​3}},下面的内容应该在DB2中起作用

WITH T AS
(
SELECT *,
       ROW_NUMBER() OVER (PARTITION BY personId ORDER BY doneOn DESC) RN
FROM WorkLog
)
SELECT personId , actionType , doneOn 
FROM T
WHERE RN=1