每个user_id的SQL增量ID

时间:2013-07-14 11:57:24

标签: sql postgresql

我有数据:

user_id  user_login_date
1        2013.07.05 
1        2013.07.15
1        2013.07.16
1        2013.07.17
2        2013.07.05
2        2013.07.05
2        2013.07.15

我想制作看起来像这样的虚拟表:

user_id  user_login_date date_id
1        2013.07.05      1
1        2013.07.15      2
1        2013.07.16      3
1        2013.07.17      4
2        2013.07.05      1
2        2013.07.05      2
2        2013.07.15      3

我该怎么做? 我试过了:

WITH user_count
AS (
  SELECT user_id, user_login_date
  FROM users
)
SELECT user_count.user_id, user_count.user_login_date, COUNT(user_count.user_id)
FROM users, user_count
WHERE users.user_login_date >= user_count.user_login_date
AND users.user_id = user_count.user_id
GROUP BY user_count.user_id, user_count.user_login_date
ORDER BY user_count.user_id, user_count.user_login_date;

但结果不是我想要的。

2 个答案:

答案 0 :(得分:2)

select
    user_id, user_login_date,
    row_number() over(
        partition by user_id
        order by user_login_date
    ) as date_id
from users
order by user_id, date_id

答案 1 :(得分:0)

select  row_number() over (partition by user_id order by user_login_date) as date_id
,       yt.*
from    YourTable yt