select
    ID,UserName
from
    (select 1 as type,0 as ID,'在线用户' as UserName 
     union all
     select 1 ,ID,UserName from Table where datediff(ss,AddTime,getdate())<=60
     union all
     select 2 as type,0 as ID,'离线用户' as UserName 
     union all
     select 1 ,ID,UserName from Table where datediff(ss,AddTime,getdate())>60) a
order by
    type,ID

解决方案 »

  1.   

    Select 0 As id,N'在线用户' As username
    Union All
    Select id,username from [Table] Where DateDiff(mi,AddTime,GetDate())<=1
    Union All
    Select 0 As id,N'离线用户' As username
    Union All
    Select id,username from [Table] Where DateDiff(mi,AddTime,GetDate())>1
      

  2.   

    --生成测试数据
    create table #t(ID int,UserName varchar(20),AddTime datetime)
    insert into #t select 1,'a','2005-6-11 13:09:31'
    insert into #t select 2,'b','2005-6-12 13:09:31'
    insert into #t select 3,'c','2005-6-14 11:08:31'
    insert into #t select 4,'d','2005-6-14 13:09:20'
    insert into #t select 5,'e','2005-6-14 13:09:31'
    --执行查询
    select
        a.ID,a.UserName
    from
        (select 1 as type,0 as ID,'在线用户' as UserName
         union all
         select 1 as type,ID,UserName from #t where datediff(ss,AddTime,'2005-6-14 13:09:40')<=60
         union all
         select 2 as type,0 as ID,'离线用户' as UserName
         union all
         select 2 as type,ID,UserName from #t where datediff(ss,AddTime,'2005-6-14 13:09:40')>60) a
    order by
        a.type,a.ID
    --输出结果
    ID     UserName
    -----  --------
    0      在线用户
    4      d
    5      e
    0      离线用户
    1      a
    2      b
    3      c
      

  3.   

    借用红尘的数据--生成测试数据
    create table #t(ID int,UserName varchar(20),AddTime datetime)
    insert into #t select 1,'a','2005-6-11 13:09:31'
    insert into #t select 2,'b','2005-6-12 13:09:31'
    insert into #t select 3,'c','2005-6-14 11:08:31'
    insert into #t select 4,'d','2005-6-14 13:09:20'
    insert into #t select 5,'e','2005-6-14 13:09:31'
    --测试
    Select 0 As id,N'在线用户' As username
    Union All
    Select id,username from [#t] Where DateDiff(mi,AddTime,'2005-6-14 13:09:40')<=1
    Union All
    Select 0 As id,N'离线用户' As username
    Union All
    Select id,username from [#t] Where DateDiff(mi,AddTime,'2005-6-14 13:09:40')>1
    --结果
    /*
    id Name
    0 在线用户
    4 d
    5 e
    0 离线用户
    1 a
    2 b
    3 c
    */