有这样一个数据库
姓名  旷工日期
张三  2011-9-14
张三  2011-9-15
张三  2011-9-16
李四  2011-9-10
李四  2011-9-12
李四  2011-9-14
张三  2011-9-20
显示连续旷工三天以上的数据,如张三14,15,16三天旷工的数据,并且计算连续旷工的次数

解决方案 »

  1.   

    create table tb(姓名 nvarchar(10),旷工日期 datetime)
    insert into tb select '张三','2011-9-14'
    insert into tb select '张三','2011-9-15'
    insert into tb select '张三','2011-9-16'
    insert into tb select '李四','2011-9-10'
    insert into tb select '李四','2011-9-12'
    insert into tb select '李四','2011-9-14'
    insert into tb select '张三','2011-9-20'
    go
    select a.姓名,a.旷工日期,b.旷工日期,c.旷工日期
    from tb a inner join tb b on a.姓名=b.姓名 and datediff(d,a.旷工日期,b.旷工日期)=1
    inner join tb c on c.姓名=b.姓名 and datediff(d,b.旷工日期,c.旷工日期)=1
    /*
    姓名         旷工日期                    旷工日期                    旷工日期
    ---------- ----------------------- ----------------------- -----------------------
    张三         2011-09-14 00:00:00.000 2011-09-15 00:00:00.000 2011-09-16 00:00:00.000(1 行受影响)*/
    go
    drop table tb
      

  2.   


    select name , not_worktime
    from tablename  t
    where  exists(select 1 from tablename where datediff(day,t.not_worktime,not_worktime)=1)
    and  exists(select 1 from tablename where datediff(day,t.not_worktime,not_worktime)=2)
      

  3.   

    create table tb(姓名 nvarchar(10),旷工日期 datetime)
    insert into tb select '张三','2011-9-14'
    insert into tb select '张三','2011-9-15'
    insert into tb select '张三','2011-9-16'
    insert into tb select '李四','2011-9-10'
    insert into tb select '李四','2011-9-12'
    insert into tb select '李四','2011-9-14'
    insert into tb select '张三','2011-9-20'
    go
    ;with cte as(
    select *,1 as 连续旷工天数 from tb a where not exists(select 1 from tb where 姓名=a.姓名 and datediff(d,旷工日期,a.旷工日期)=1)
    union all
    select a.*,b.连续旷工天数+1 from tb a inner join cte b on a.姓名=b.姓名 and datediff(d,b.旷工日期,a.旷工日期)=1
    )select * from cte order by 1,2
    /*
    姓名         旷工日期                    连续旷工天数
    ---------- ----------------------- -----------
    李四         2011-09-10 00:00:00.000 1
    李四         2011-09-12 00:00:00.000 1
    李四         2011-09-14 00:00:00.000 1
    张三         2011-09-14 00:00:00.000 1
    张三         2011-09-15 00:00:00.000 2
    张三         2011-09-16 00:00:00.000 3
    张三         2011-09-20 00:00:00.000 1(7 行受影响)*/
    go
    drop table tb
      

  4.   

    请问楼上,可以改成SQL2000版的吗,WITH AS 语句在能在SQL2005里面可以用