0
我想在T-SQL公用表表達式中使用開始和結束日期參數。我對SQL Server開發非常陌生,我不確定在查詢中缺少什麼。在SQL Server CTE中使用日期參數
我可以指定值爲@startdate
& @enddate
並得到正確的結果。
但是,我想弄清楚如何打開這兩個參數,以便用戶可以指定開始日期和結束日期值。該查詢將用於SSRS報告中。
DECLARE @startdate Datetime,
@enddate Datetime;
SET @startdate = '2017-02-09';
SET @enddate = '2017-02-10';
WITH ManHours AS
(
SELECT DISTINCT
a.plant_name AS Plant, SUM(tc.total_hr) AS TotalHours
FROM
area AS a
INNER JOIN
tf_department AS dep ON a.plant_id = dep.plant_id
INNER JOIN
tf_timecard AS tc ON dep.department_id = tc.department_id
WHERE
tc.timecard_dt BETWEEN @startdate AND @enddate
AND tc.department_id IN (266, 453, ...endlessly long list of IDs......)
AND tc.hourtype_id = 1
GROUP BY
a.plant_name),
Tonnage AS
(
SELECT DISTINCT
a.plant_name AS Plant, SUM(tglt.postqty) AS TotalTonnage
FROM
area AS a
INNER JOIN
plantgl AS pgl ON a.plant_id = pgl.plant_id
INNER JOIN
tgltransaction AS tglt ON pgl.glacckey = tglt.glacctkey
WHERE
tglt.postdate BETWEEN @startdate AND @enddate
GROUP BY
a.plant_name
)
SELECT DISTINCT
ManHours.Plant,
SUM(TotalTonnage) as 'Production Tons' ,
SUM(TotalHours) as 'Man Hours',
TotalTonnage/TotalHours AS TonsPerManHour
FROM
ManHours
LEFT OUTER JOIN
Tonnage ON ManHours.Plant = tonnage.Plant
GROUP BY
ManHours.Plant, ManHours.TotalHours, Tonnage.TotalTonnage
將此查詢包裝在存儲過程中 – TheGameiswar
您可以刪除DECLARE和SET語句。當您將其餘查詢放入SSRS中的數據集時,它將自動創建兩個參數。您只需將參數更改爲DATE類型,並且會在運行查詢之前提示輸入日期。 –