ID  人员ID     起始日期     终止日期     办事处     调整原因
1     1001     2010-1-1      2010-3-31    南京       业务需要
2     1001     2010-4-1      至现在       上海       <null>
3     1002     2010-2-1      2010-3-28     广州       不适应
4     1002     2010-3-29      至现在       珠海       <null>
现在有个需求:
 比如:我输入:2010-3-1 -----2010-3-31
 得到的统计表是:
     人员ID     调整日期     调整描述     调整原因
     1002      2010-3-28   广州----珠海    不适应
     1001      2010-3-31   南京----上海    业务需要
通过SQL语句实现.

解决方案 »

  1.   


    create proc aaa @stime datetime,@etime datetime
    select * from tb where 起始日期>@stime and 终止日期<@etime
      

  2.   

    你输入的时间是在哪里输入?作为存储过程的参数还是直接放入sql语句中
      

  3.   

    where 终止日期 between '2010-3-1' and '2010-3-31'
      

  4.   

    if not object_id('tb') is null
    drop table tb
    Go
    Create table tb([ID] int,[人员ID] int,[起始日期] Datetime,[终止日期] nvarchar(9),[办事处] nvarchar(2),[调整原因] nvarchar(4))
    Insert tb
    select 1,1001,'2010-1-1',N'2010-3-31',N'南京',N'业务需要' union all
    select 2,1001,'2010-4-1',N'至现在',N'上海',null union all
    select 3,1002,'2010-2-1',N'2010-3-28',N'广州',N'不适应' union all
    select 4,1002,'2010-3-29',N'至现在',N'珠海',null
    Go
    select 人员ID,
           终止日期,
           办事处+'---'+(select top 1 办事处 
                         from tb
                         where [人员ID]=t.[人员ID] and ID>t.id )调整描述,
           调整原因
    from tb t
    where [终止日期]between '2010-3-1' and '2010-3-31'
    /*
    人员ID        终止日期      调整描述    调整原因
    ----------- --------- ------- ----
    1001        2010-3-31 南京---上海 业务需要
    1002        2010-3-28 广州---珠海 不适应(2 個資料列受到影響)
    */
      

  5.   


    create table #test(ID int,人员ID  int,起始日期 datetime,终止日期 datetime,办事处 varchar(20),调整原因 varchar(20))insert #test select 1 ,1001 ,'2010-1-1','2010-3-31', '南京', '业务需要'
    insert #test select 2 ,1001 ,'2010-4-1',getdate(), '上海', null
    insert #test select 3 ,1002 ,'2010-2-1',' 2010-3-28', '广州', '不适应'
    insert #test select 4 ,1002 ,'2010-3-29',getdate(), '珠海', nulldeclare @begin datetime,@end datetime
    set @begin='2010-3-1'
    set @end='2010-3-31';with cte as(select *,rn=row_number() over(partition by 人员ID order by 起始日期) from #test)
    ,cte1 as(
    select a.*,a.办事处+isnull('---'+b.办事处,'') as 调整描述 from cte a left join cte b on a.人员ID=b.人员ID and a.id=b.id-1)
    select 人员ID,终止日期 as 调整日期
    ,调整描述
    ,调整原因
    from cte1 
    where 终止日期 between @begin and @end人员ID        调整日期                    调整描述                                        调整原因
    ----------- ----------------------- ------------------------------------------- --------------------
    1001        2010-03-31 00:00:00.000 南京---上海                                     业务需要
    1002        2010-03-28 00:00:00.000 广州---珠海                                     不适应(2 行受影响)