我在postgres表中有以下数据:
user id time_stamp action
1 '2014-12-04 17:44:46+00' sign up
1 '2015-03-26 15:06:27+00' work out
3 '2015-02-09 11:40:25+00' sign up
我想要的是创建第4列
根据时间戳计算用户所做的操作,如下所示:
user id time_stamp action event id
1 '2014-12-04 17:44:46+00' sign up 1-1 ( 1st action of user id 1
1 '2015-03-26 15:06:27+00' work out 1-2 (2nd action of user id 1
3 '2015-02-09 11:40:25+00' sign up 2-1 ( 1st actoin of user id 1
这个问题一直困扰着我几个月..真的很感激,如果有人能帮助我解决它或指导我朝着正确的方向发展..
答案 0 :(得分:1)
您应该使用row_number()
功能。假设您的表名是users
:
alter table users add column event_id text;
update users t
set event_id = e_id
from (
select *,
format('%s-%s', user_id, row_number() over (partition by user_id order by time_stamp)) as e_id
from users
order by 1, 2
) sub
where sub.user_id = t.user_id and sub.time_stamp = t.time_stamp;