0

我試圖創建一個腳本來計算存儲過程的預期結果。有幾個與sp共享一個BatchId的表。 x_NonFullTimeEmployees有一個StatusString列,其長度等於MeasurementStartDateMeasurementStartDate之間的時間段。 I.E.對於7天的期限,它可能看起來像'TAAAAAA'。我在同一時間段內選擇時間卡並總結其值。我的問題是我只想使用StartDate在StatusString中由'A'表示的那一天的TimeCard值。我怎樣才能做到這一點?如何根據日期範圍內的日期選擇子字符串

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

首先我想說,你的查詢真的是一團糟。所有的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 
+0

謝謝湯姆,對不起馬虎。我剛剛開始我的SQL培訓 –

+0

請您詳細說明加入請 –

+0

@AntarrByrd例如'WHERE ... AND tc.OrganizationId =(SELECT TOP1 OrganizationId FROM CTE_ACTIVENFS)'應該是'FROM TimeCard tc INNER JOIN CTE_ACTIVENFS hire ON ... AND tc.OrganizationId = hire.OrganizationId',順便說一句,我不認爲你真的需要第一個CTE – TomT