表Table1数据记录:
Rid(int 自增)  begindate(datetiem,入库时间)    enddate (datetiem 出库时间)     Uid(UserID)  Flag
1               2010-04-15 06:00:00.000      2011-07-12 07:00:00.000                 U001         
2               2010-04-15 08:19:00.000      2011-07-12 12:19:00.000                 U001
3               2010-04-15 15:19:00.000      2011-07-12 19:19:00.000                 U001
4               2010-04-15 08:19:00.000      2010-04-15 20:19:00.000                 U002        
5               2010-04-16 06:19:00.000      2011-07-12 19:19:00.000                 U001 
 车库入出库规定时间:早6:00-晚:21:00车主每天可能有一次或多次出入车记录.
对于一天仅一次的:
如果在入出库时间在(6:00AM-21:00PM)内,则Flag标记为"A";
如入库时间晚于6:00AM,则Flag标记为"B"(不用考虑出库时间);
如出库时间晚于21:00PM,则Flag标记为"C"(不用考虑入库时间).对于一天多次的:
[情况1].如果他首次入库时间和他末次的出库时间在(6:00AM-21:00PM)内,则Flag标记为"A";
[情况2].如果他首次入库时间晚于(大于)6:00AM,则Flag标记为"B"(不用考虑末次出库时间);
[情况3].如果他末次出库时间早于(没错,是早于)21:00PM,则Flag标记为"C"(不用考虑首次入库时间)。(注意:文中首次和末次涉及多条记录,就是说每个车主一天多次入出库的返回的数据结果集只保留一条记录。[如出现2、3情况交,则优先级情况2>情况3,即优先显示情况2。]) 根据上述需求,请高手写出返回结果集SQL?

解决方案 »

  1.   

    同问  跨天就不好做了 同一天的直接可以case when 列举
      

  2.   

    一天单条的case when 好搞定,多条的?
      

  3.   

    update t set
      Flag =case when not exists (
        select 1 from Table1 where Uid = t.Uid and (datepart(hour,begindate)<6
            or datepart(hour,begindate)>=21)
            )
          then 'A'
         when exists (
        select 1 from Table1 where Uid = t.Uid and datepart(hour,begindate)<6
            )
          then 'B'
         else 'C'
        end
    from Table1 t
      

  4.   

    如果在入出库时间在(6:00AM-21:00PM)内,则Flag标记为"A";
    如入库时间晚于6:00AM,则Flag标记为"B"(不用考虑出库时间);
    如出库时间晚于21:00PM,则Flag标记为"C"(不用考虑入库时间).
    这里表述是否有问题
    晚于6:00AM包括6:00AM-21:00PM
      

  5.   


    update t set
      Flag =case when not exists (
        select 1 from Table1 where Uid = t.Uid and (datepart(hour,begindate)<6
            or datepart(hour,enddate)>=21)
            )
          then 'A'
         when exists (
        select 1 from Table1 where Uid = t.Uid and datepart(hour,begindate)<6
            )
          then 'B'
         else 'C'
        end
    from Table1 t
      

  6.   

    6楼,你好,不是每条记录都去更新标记flag的值,而是查询,用select ,case when .....之类的返回结果集
      

  7.   

    不想猜你的意思了,你列出各种情况的例子,表示清楚正确的Flag这问题一点都不典型
      

  8.   

    select *,Flag =case when not exists (
        select 1 from Table1 where Uid = t.Uid and (datepart(hour,begindate)<6
            or datepart(hour,enddate)>=21)
            )
          then 'A'
         when exists (
        select 1 from Table1 where Uid = t.Uid and datepart(hour,begindate)<6
            )
          then 'B'
         else 'C'
        end
    from Table1 t
      

  9.   

    结果集实际上上面已经说了,同一天多次的记录,只要返回一条记录,且标记flag的值,如果一天只有一条记录标记flag的值那就很好判断了,其它条件根据上面的说明。