2013-07-14 43 views
0

我有數據:SQL增量ID user_id說明

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
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 
0
select row_number() over (partition by user_id order by user_login_date) as date_id 
,  yt.* 
from YourTable yt