我尝试创建一个计算存储过程的预期结果的脚本。有几个与sp相关的表共享一个BatchId。 x_NonFullTimeEmployees
有一个StatusString
列,其长度等于MeasurementStartDate
和MeasurementStartDate
之间的时间段。 I.E.在7天的时间内,它可能看起来像'TAAAAAA'
。我在同一时期选择时间卡并总结他们的价值观。我的问题是我只想使用TimeCard值,其中StartDate所代表的日期为' A'在StatusString中。我怎么能这样做?
DECLARE @batchid INT = 1;
WITH CTE_ACTIVENFS
AS
(
select e.EmployeeId,e.OrganizationId,e.MeasurementStartDate, e.MeasurementEndDate
from x_VHEActiveNonFullTimeEmployees e
where BatchId = @batchid
)
,
CTE_RESULTS
AS
(
SELECT tc.OrganizationId ,tc.EmployeeId, SUM(tc.workhour) AS "Total Paid Hours",
DATEDIFF(month, (SELECT TOP 1 StartDate FROM TimeCard WHERE EmployeeId = tc.EmployeeId),(SELECT TOP 1 StartDate FROM TimeCard WHERE EmployeeId = tc.EmployeeId ORDER BY StartDate DESC))
AS "Total Paid Period",
SUM(tc.workhour)/ DATEDIFF(month, (SELECT TOP 1 StartDate FROM TimeCard WHERE EmployeeId = tc.EmployeeId),(SELECT TOP 1 StartDate FROM TimeCard WHERE EmployeeId = tc.EmployeeId ORDER BY StartDate DESC))
AS "Average Worked Hours"
FROM TimeCard tc INNER JOIN CTE_ACTIVENFS hire ON hire.EmployeeId = tc.EmployeeId
WHERE tc.EmployeeId IN (SELECT EmployeeId FROM CTE_ACTIVENFS)
AND tc.StartDate BETWEEN (SELECT TOP 1 MeasurementStartDate FROM CTE_ACTIVENFS) AND (SELECT TOP 1 MeasurementEndDate FROM CTE_ACTIVENFS)
AND tc.OrganizationId = (SELECT TOP 1 OrganizationId FROM CTE_ACTIVENFS)
GROUP BY tc.EmployeeId, tc.OrganizationId
)
SELECT * FROM CTE_RESULTS
答案 0 :(得分:1)
首先,我想说你的查询确实很乱。所有SELECT TOP 1
都应该合并为连接。现在,对于你的问题,我做这样的事情:
select *
from x_NonFullTimeEmployees hire
inner join timecard tc
on tc.EmployeeId = hire.EmployeeId
and tc.StartDate between hire.MeasurementStartDate and hire.MeasurementEndDate
and substring(
hire.StatusString,
datediff(dd, hire.MeasurementStartDate, tc.StartDate) +1,
1) = 'A'
where hire.BatchId = @batchid