如何根据日期范围内的日期选择子字符串

时间:2014-03-31 20:58:39

标签: sql-server sql-server-2012 substring common-table-expression date-range

我尝试创建一个计算存储过程的预期结果的脚本。有几个与sp相关的表共享一个BatchId。 x_NonFullTimeEmployees有一个StatusString列,其长度等于MeasurementStartDateMeasurementStartDate之间的时间段。 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

1 个答案:

答案 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