【发布时间】:2015-09-10 14:30:35
【问题描述】:
我正在尝试获取仍在工作的员工和八月份辞职的员工的记录。这是我的查询:
DECLARE @MontStart datetime,@MonthEnd datetime
set @MontStart =cast('8/1/2015' as datetime)
set @MonthEnd = cast('8/31/2015' as datetime)
Select * from ( Select EmployeeNo, (Select LastName+','+FirstName from EmpPersonalInfo where EmployeeNo=s1.EmployeeNo) as EmployeeName,(Select Classtitle from Classification where ClassCode=s1.ClassCode) as Classification,Status,s1.EffectivityDateFrom,s1.EffectivityDateTo,
ROW_NUMBER() OVER (PARTITION BY EmployeeNo ORDER BY Status desc,cast(EffectivityDateTo as date) desc) AS Priority
FROM Employmenthistory s1)S2 where Priority=1 and (LTRIM(RTRIM(EmployeeNo))<>'' and NOT(EmployeeNo=''))
AND (@MontStart >= cast(EffectivityDateFrom as datetime) and (cast(EffectivityDateTo as datetime)>=@MontStart or (cast(EffectivityDateTo as datetime)<=@MonthEnd OR EffectivityDateTo is null)))
order by EmployeeName
但是这个查询也会返回那些在过去几个月和几年内辞职的员工。
这是结果。
EffectivityDateTo 列的 NULL 值表示该员工仍在受雇 (Status=1)。
状态 1 = 在职/在职。
状态 0 = 非活动
员工 901790 仍然活跃,尽管他的 EmployedTo 是 2010 年,但他仍然设置为活跃
EmployeeNo | EmployeeName | Status | EmployedFrom | EmployedTo
901790 | EmpName1 | 1 | 2008-07-28 | 2010-07-31
902566 | EmpName2 | 1 | 2013-01-25 | 2013-12-13
902502 | EmpName3 | 1 | 2012-08-15 | NULL
902309 | EmpName4 | 0 | 2011-07-12 | 2015-08-14
902575 | EmpName5 | 0 | 2013-03-11 | 2015-08-14
902706 | EmpName6 | 1 | 2014-03-24 | 2015-10-10
预期结果是这样的:
EmployeeNo | EmployeeName | Status | EmployedFrom | EmployedTo
902502 | EmpName3 | 1 | 2012-08-15 | NULL
902309 | EmpName4 | 0 | 2011-07-12 | 2015-08-14
902575 | EmpName5 | 0 | 2013-03-11 | 2015-08-14
902706 | EmpName6 | 1 | 2014-03-24 | 2015-10-10
【问题讨论】:
-
请用随机数据设置sqlfiddle.com,这样会更容易帮助。
-
感谢您的建议!
-
您需要修复 WHERE 子句。您的第一个谓词表示获取在 8 月 1 日之前开始的任何员工。然后您有一个 AND,其中包含 3 个 OR 子句。如果任何 OR 子句的计算结果为真,您将获得记录。这是该组 3 中的特定 OR 子句,它允许您的查询返回较旧的记录: OR (cast(EffectivityDateTo as datetime)
-
谢谢@PeterDNCO。我尝试修改我的 WHERE 子句,但不幸的是得到了预期的结果。你能帮我吗?
-
将源数据添加到您的问题中以获得好的答案。或者放在sqlfiddle中。
标签: sql sql-server