Question

I'm trying to create a script that calculates the expected results from a stored procedure. There are several tables related to the sp that share a BatchId. x_NonFullTimeEmployees has a StatusString column whose length is equal the the period between that MeasurementStartDate and the MeasurementStartDate. I.E. for a 7 day period it may look like 'TAAAAAA'. I am selecting time cards in the same period and summing their values. My problem is I only want to use the TimeCard values where the StartDate is on a day represented by 'A' in the StatusString. How can I do this?

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
Was it helpful?

Solution

First I'd like to say that your query is really a mess. All the SELECT TOP 1 should be truned into joins. Now for your question, I'd do it something like this:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top