-1
我有一個場景來顯示來自2個表合併的數據。第一張表名爲'DayTable'由每日計劃和實際組成。名爲「MonthTable」的第二張表包含每月計劃和實際。我需要顯示最近6個月的數據和當前的每日數據。所以我寫了下面我喜歡的查詢的預期產出子查詢中的CTE
Declare @startdate date = CONVERT(DATE, DATEADD(dd, -DAY(DATEADD(MONTH, 0, GETDATE())) + 1, DATEADD(MONTH, 0, GETDATE())))
Declare @endDate date = DATEADD(DAY, -DAY(DATEADD(MONTH, 1, GETDATE())), DATEADD(MONTH, 1, GETDATE()))
CREATE TABLE #TEMP
(
PlanDate NVARCHAR(100),
[PastTrend - Plan] INT,
[PastTrend - Actual] INT,
[Current - Plan] INT,
[Current - Actual] INT,
)
;With cte
as
(
Select @startdate sDate
Union All
Select DATEADD(day,1,sDate) From cte where DATEADD(day,1,sDate) <= @endDate
)
INSERT INTO #TEMP
SELECT
REPLACE(CONVERT(CHAR(6), A.sDate, 106),' ',' - ') PlanDate
,NULL AS [PastTrend - Plan]
,NULL AS [PastTrend - Actual]
,SUM(B.PlanQuantity) AS [Current - Plan]
,SUM(B.Actual) AS [Current - Actual]
FROM cte A
LEFT OUTER JOIN DayTable B
ON A.sDate = CONVERT(DATE,B.PlanDate)
GROUP BY A.sDate
--ORDER BY A.sDate
SELECT
*
FROM
(
SELECT
CONVERT(CHAR(3), datename(month,PlanMonth)) + ' ' + RIGHT(CONVERT(VARCHAR(4), YEAR(PlanMonth)), 2) AS PlanDate
,SUM(PlanQuantity) AS [PastTrend - Plan]
,SUM(Actual) AS [PastTrend - Actual]
,NULL AS [Current - Plan]
,NULL AS [Current - Actual]
FROM
MonthTable
WHERE CONVERT(DATE, PlanMonth) >= CONVERT(DATE, DATEADD(dd, -DAY(DATEADD(MONTH, 0, GETDATE())) + 1, DATEADD(MONTH, -6, GETDATE())))
group by PlanMonth
UNION ALL
SELECT
PlanDate
,[PastTrend - Plan]
,[PastTrend - Actual]
,[Current - Plan]
,[Current - Actual]
FROM
#TEMP
) T1
DROP TABLE #TEMP
我的輸出是一樣
現在我稀化,以避免臨時表的概念,因爲如果出現任何故障創建臨時表之後不會下降。所以重寫下面的查詢
Declare @startdate date = CONVERT(DATE, DATEADD(dd, -DAY(DATEADD(MONTH, 0, GETDATE())) + 1, DATEADD(MONTH, 0, GETDATE())))
Declare @endDate date = DATEADD(DAY, -DAY(DATEADD(MONTH, 1, GETDATE())), DATEADD(MONTH, 1, GETDATE()))
;With cte
as
(
Select @startdate sDate
Union All
Select DATEADD(day,1,sDate) From cte where DATEADD(day,1,sDate) <= @endDate
)
SELECT
A.sDate AS OriginalDate
,REPLACE(CONVERT(CHAR(6), A.sDate, 106),' ',' - ') PlanDate
,NULL AS [PastTrend - Plan]
,NULL AS [PastTrend - Actual]
,SUM(B.PlanQuantity) AS [Current - Plan]
,SUM(B.Actual) AS [Current - Actual]
FROM cte A
LEFT OUTER JOIN DayTable B
ON A.sDate = CONVERT(DATE,B.PlanDate)
GROUP BY A.sDate
UNION ALL
SELECT
PlanMonth AS OriginalDate
,CONVERT(CHAR(3), datename(month,PlanMonth)) + ' ' + RIGHT(CONVERT(VARCHAR(4), YEAR(PlanMonth)), 2) AS PlanDate
,SUM(PlanQuantity) AS [PastTrend - Plan]
,SUM(Actual) AS [PastTrend - Actual]
,NULL AS [Current - Plan]
,NULL AS [Current - Actual]
FROM
MonthTable
WHERE CONVERT(DATE, PlanMonth) >= CONVERT(DATE, DATEADD(dd, -DAY(DATEADD(MONTH, 0, GETDATE())) + 1, DATEADD(MONTH, -6, GETDATE())))
group by PlanMonth
ORDER BY OriginalDate
但在這裏我有問題。在輸出我不需要OriginalDate。如何避免這一點。爲此,我可以將聯合輸出包裝爲一個選擇查詢,但是如何在cte中得到錯誤。請指導我。還建議哪種方法最好一個
爲什麼不只是在臨時表中包含「IF EXISTS .... DROP」?你也可以考慮一個'TRY..CATCH'邏輯來刪除臨時表,以防止失敗 – Raj
是一個好主意。但我試圖避免臨時表。我不知道哪種方法好。我認爲直接的方法很簡單,很好。也是這樣,我有其他程序也使用溫度。所以想避免它。就這樣。如果臨時表是更好的方法,我可以這樣做 – Akhil