日期:2014-05-18  浏览次数:20515 次

请问这个SQL查询怎么实现,非常感谢,请进
有一张员工信息表,表结构如下:
员工号(userid),员工名(username),入职日期(effectdate),离职日期(leavedate)
==========================================================================
现在需要完成一个查询,条件如下:
1、首先要离职月份<=1个月(包括没有离职数据的,也就是leavedate为null)的员工,然后再以下面两个条件筛选
2、入职日期>=4号,考评月份-入职月份>=4个月,符合条件者,显示
3、入职日期<4号:
case   1号:考评月份-入职月份>=3个月,符合条件者显示
case   2号:when   1号星期天,考评月月份-入职月月份>=3个月,符合条件者显示
                    else   考评月月份-入职月月份>=4个月,符合条件者显示
case   3号:when   1号星期六,考评月月份-入职月月份>=3个月,符合条件者显示
                    else   考评月月份-入职月月份>=4,符合条件者显示
==========================================================================
其中“考评月份”,是一个参数,先假设为“2007年07月”。


------解决方案--------------------
declare @考评月份 datetime
set @考评月份= '2007-7-1 '

select * from 员工信息表 a
where (离职日期 is null or 离职日期 <dateadd(month,-1,@考评月份))
and (
day(入职日期)> =4 and datediff(month,入职日期,@考评月份)> =4
or day(入职日期)=1 and datediff(month,入职日期,@考评月份)> =3
or day(入职日期) in (2,3) and datepart(weekday,入职日期)=2 and datediff(month,入职日期,@考评月份)> =3
or day(入职日期) in (2,3) and datepart(weekday,入职日期) <> 2 and datediff(month,入职日期,@考评月份)> =4
)


------解决方案--------------------
嗯,可以合并


select *
from tablename
where (leavedate > =dateadd(mm,-1,getdate()) or leavedate is null)
and(
day(effectdate) > = 4 and datediff(mm,effectdate,考评月份) > = 4
or day(effectdate) = 1 and datediff(mm,effectdate,考评月份) > = 3
or day(effectdate) in (2,3) and datepart(dw,effectdate) = 1 and datediff(mm,effectdate,考评月份) > = 3
or day(effectdate) in (2,3) and datepart(dw,effectdate) <> 1 and datediff(mm,effectdate,考评月份) > = 4
)


------解决方案--------------------
-- 上面的写错了,以这个为准
declare @table table(userid varchar(10),username varchar(20),effectdate datetime,leavedate datetime)
insert into @table
select '0001 ', '张三 ', '2007-01-01 ', '2007-06-20 '
union all select '0002 ', '李四 ', '2007-04-01 ',null
union all select '0003 ', '王五 ', '2007-03-01 ',null
union all select '0004 ', '赵六 ', '2007-03-02 ',null
union all select '0005 ', '刘七 ', '2007-04-02 ',null
union all select '0006 ', '李二 ', '2007-04-03 ',null
declare @cMonth datetime
set @cMonth= '2007-07-31 '--将日期设为考评月份的最后一天

select userid,username,effectdate,leavedate
from @table
where datediff(mm,isnull(leavedate,convert(datetime, '9999-12-31 ')),@cMonth) <=1 and
((datediff(mm,effectdate,@cMonth)> =4)or
(day(effectdate) <4 and
(datepart(dw,convert(datetime,cast(year(effectdate)as char(4))+ '- '+right(100+month(effectdate),2)+ '-01 '))in(1,7))
and datediff(mm,effectdate,@cMonth)> =3)or
(day(effectdate)=1 and datediff(mm,effectdate,@cMonth)> =3))

/*结果
userid username effectdate leavedate
---------- -------------------- ----------------------- -----------------------
0001 张三 2007-01-01 00:00:00.000 2007-06-20 00:00:00.000
0002 李四 2007-04-01 00:00:00.000 NULL
0003 王五 2007-03-01 00:00:00.000 NULL
0004 赵六 2007-03-02 00:00:00.000 NULL
0005 刘七 2007-04-02 00:0