有个表Log,有字段id,type,time。type=0表示用户进入,type=1表示用户离开
Log
id  type  time
0    0    1
0    1    2
1    0    4
1    1    5
0    0    6
0    1    8
2    0    9现在希望显示如下信息
Out
id in_time out_time
0  1       2
0  6       8
1  4       5
2  9       null
按用户显示其进入时间和离开时间
如何写SQL?

解决方案 »

  1.   

    select id,case when type=0 then time end as in_time,case when type=1 then time end as out_tim
    from Log
      

  2.   

    select id,time as in_time,out_time=(select top 1 time from log b where b.type=1 and a.id=b.id and b.time>a.time order by time) from log a
    where type=0
      

  3.   

    select
        a.id,a.time as in_time,min(b.time) as out_time
    from
        log a
    left join
        log b
    where
        a.id=b.id and a.time<b.time
    group by
        a.id,a.time
      

  4.   

    select
        a.id,a.time as in_time,min(b.time) as out_time
    from
        log a
    left join
        log b
    on
        a.id=b.id and b.type=1 and a.time<b.time
    where
        a.type=0
    group by
        a.id,a.time
      

  5.   

    declare @Log table(id int,type int,time int)
    insert into @Log select 0,0,1
    insert into @Log select 0,1,2
    insert into @Log select 1,0,4
    insert into @Log select 1,1,5
    insert into @Log select 0,0,6
    insert into @Log select 0,1,8
    insert into @Log select 2,0,9
    select
        a.id,a.time as in_time,min(b.time) as out_time
    from
        @log a
    left join
        @log b
    on
        a.id=b.id and b.type=1 and a.time<b.time
    where
        a.type=0
    group by
        a.id,a.time/*
    id          in_time     out_time    
    ----------- ----------- ----------- 
    0           1           2
    1           4           5
    0           6           8
    2           9           NULL
    */
      

  6.   

    谢谢
    还想继续问一下,如果log表是某条select语句的查询结果
    合起来应该如何写?
      

  7.   

    将语句里有log的地方换成你的查询语句,两头加上括号即可
      

  8.   

    有log的地方都要换?
    只换其中某个可以吗?
      

  9.   

    我这个SQL比较长,而且里面有case关键字
    建视图时提示查询设计器不支持 CASE SQL 构造。
      

  10.   

    maple0112() ( ) 信誉:100    Blog   加为好友  2007-04-13 11:42:23  得分: 0  
     
     
       提点意见,首先要保证进入和离开这两条数据一定要有健全机制保证成对出现,那么查询才有意义。
      
     
    同意以上观点,你这个表设计的就有问题
      

  11.   

    SELECT intime.Id,intime.time in_time,min(outtime.time) out_time
    FROM (
    SELECT id,time
    FROM Log intime
    WHERE type=0
    )intime LEFT JOIN (
    SELECT id,time
    FROM Log outtime
    WHERE type=1
    )outtime
    ON intime.id=outtime.Id
    AND intime.time<outtime.time
    GROUP BY intime.Id,intime.time
    ORDER BY intime.Id
    表结构设计有问题,不然也不至于如此麻烦。
      

  12.   

    应该再加一个字段group2,标识那两条是属于同组的纪录(需要在写程序的时候合理判断),即为1,2,3.....然后sql就很容易查了