sql序列的时间

时间:2014-08-04 19:02:46

标签: sql sql-server date sequence

我正在寻找帮助,在我的表中添加一个列,其中每行的序列(1,2,3 ...)基于日期并按userID分组,如下面的模型所示。不确定我是否必须自己加入表并计算,或者是否有更高效的功能。我正在使用SQL Server 2008 R2。

| Username  | Date      | 
--------------------------
| Username1 | 01/1/2014 | 
| Username1 | 02/1/2014 | 
| Username1 | 03/1/2014 |
| Username2 | 01/4/2014 | 
| Username2 | 01/6/2014 | 
| Username3 | 02/3/2014 |
| Username3 | 05/8/2014 |
| Username4 | 01/9/2014 |
| Username1 | 08/1/2014 | 
| Username5 | 07/1/2014 | 

| Username  | Date      |Seq |
------------------------------
| Username1 | 01/1/2014 | 1  |
| Username1 | 02/1/2014 | 2  |
| Username1 | 03/1/2014 | 3  |
| Username2 | 01/4/2014 | 1  | 
| Username2 | 01/6/2014 | 2  |
| Username3 | 02/3/2014 | 1  | 
| Username3 | 05/8/2014 | 2  |
| Username4 | 01/9/2014 | 1  | 
| Username1 | 08/1/2014 | 4  |
| Username5 | 07/1/2014 | 1  |

2 个答案:

答案 0 :(得分:1)

按用户名分区的行号:

select 
    username, 
    date,
    row_number() over(partition by username order by username, date) as seq
from T

答案 1 :(得分:1)

这适用于row_number()函数:

select username, date, row_number() over (partition by username order by date) as seq
from mytable;