SQL SERVER根据条件生成行号

时间:2012-02-23 17:59:10

标签: sql-server-2008

我有一个包含UserID,DIFFTIME列的表。当我从表中选择这些列时,我还想要一个派生列,如果:DiffTime是> 20我想增加每个用户ID的计数。

例如,如果表格包含:

User ID DIFF TIME
 1        0
 1        5
 1        10
 2        0
 2        21
 2        5 

我想要一个类似这样的结果集:

User ID DIFF TIME SESSION NUMBER
     1        0        1
     1        5        1
     1        10       1
     2        0        1
     2        21       2
     2        5        2

我如何做到这一点。

非常感谢您的想法和建议!

2 个答案:

答案 0 :(得分:2)

使用此声明:

select t1.User_Id, t1.Diff_Time, 
    isnull(count(t2.User_Id), 0) + 1 as Session_Number
from @table t1
left join @table t2 
    on t1.User_Id = t2.User_Id 
    and t1.eventTime >= t2.eventTime 
    and t2.Diff_Time > 20
group by t1.User_Id, t1.Diff_Time, t1.eventTime
order by t1.User_Id, t1.eventTime

(用您的实际表名替换@table

注意:我假设您的表格的第五行在Diff_Time列中的值为21,并且问题中存在拼写错误,正如@AaronBertrand指出的那样在评论中

答案 1 :(得分:1)

create table #t
(
 id int,
 Diff int,
 SessionNumber int
)
insert into #t(id, diff)values(1, 0)
insert into #t(id, diff)values(1, 5)
insert into #t(id, diff)values(1, 10)
insert into #t(id, diff)values(2, 0)
insert into #t(id, diff)values(2, 21)
insert into #t(id, diff)values(2, 5)


Select ROW_NUMBER() over(order by Id) as RowID, * into #Temp1 from #t 
Declare @diff int
Declare @RowId int
Declare @Previous int
Declare @NewValue int

DECLARE @Cur CURSOR SET @Cur = CURSOR FOR select RowId, diff from #Temp1
OPEN @Cur
FETCH NEXT FROM @Cur INTO @RowId, @diff
WHILE @@FETCH_STATUS = 0
BEGIN
    if(@RowId = 1)
    Begin
        Update #Temp1 Set SessionNumber = 1 Where rowid = 1     
        Set @Previous = @Diff
        Set @NewValue = 1
    End
    Else
    Begin
        if(@Diff - @Previous > 20)
        Begin
            Set @Previous = @Diff
            Set @NewValue = @NewValue + 1
            Update #Temp1 Set SessionNumber = @NewValue Where rowid = @RowId
        End
        else
            Update #Temp1 Set SessionNumber = @NewValue Where rowid = @RowId

    End
    FETCH NEXT FROM @Cur INTO @RowId, @diff
END
CLOSE @Cur
DEALLOCATE @Cur

select * from #temp1

drop table #t
drop table #temp1