0
我試圖創建一個腳本來計算存儲過程的預期結果。有幾個與sp共享一個BatchId的表。 x_NonFullTimeEmployees
有一個StatusString
列,其長度等於MeasurementStartDate
和MeasurementStartDate
之間的時間段。 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
謝謝湯姆,對不起馬虎。我剛剛開始我的SQL培訓 –
請您詳細說明加入請 –
@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