如何逐列选择用户的最大日期?

时间:2019-06-07 08:20:18

标签: sql postgresql

我想获取userId和以userId分组的最大日期

我现在不怎么做:c 我的桌子:

Id: 1    userId:1        activitydate:2019-02-15 08:03:11
Id: 2    userId:1        activitydate:0001-01-01 00:00:00
Id: 3    userId:2        activitydate:2019-02-15 07:38:30
Id: 4    userId:2        activitydate:2019-02-15 06:30:30
Id: 5    userId:3        activitydate:2019-03-01 09:17:04



select userid,maxvalue(activitydate)
from wearabledata
group by userid

实际结果:

我的桌子:

Id: 1    userId:1        activitydate:2019-02-15 08:03:11
Id: 3    userId:2        activitydate:2019-02-15 07:38:30
Id: 5    userId:3        activitydate:2019-03-01 09:17:04

2 个答案:

答案 0 :(得分:2)

DISTINCT ON关键字正是您需要的解决方案:

SELECT DISTINCT ON (userid)
       userid,activitydate
FROM   wearabledata
ORDER  BY userid, activitydate DESC;

答案 1 :(得分:1)

SELECT
  userId,
  max(activitydate) as maxvalue
FROM
  wearabledata
GROUP BY
  userId;