我有一個SQL Server 2008上運行,它使用下面的表和他們的行數小的SQL查詢:查詢優化2008
dbo.date_master - 245424
dbo.ers_hh_forecast_consumption - 436061472
dbo.ers_hh_forecast_file - 15105
dbo.ers_ed_supply_point - 8485
我很新的SQL Server的世界,正在學習。請指導我如何能夠優化此查詢以更快地運行。
如果有人能夠提及我的錯誤以及我正在做什麼使得查詢生成的表格非常耗時,我將非常高興。
WITH CTE_CONS AS
(
SELECT T2.CONVERTED_DATE
,T1.FORECAST_FILE_ID
,SUM(T1.FORECAST_CONSUMPTION) AS TOTAL
FROM dbo.ers_hh_forecast_consumption AS T1
LEFT JOIN dbo.date_master AS T2 ON T1.UTC_DATETIME=T2.STRDATETIME
WHERE T2.CONVERTED_DATE>='2015-01-01' AND T2.CONVERTED_DATE<='2015-06-01'
GROUP BY T2.CONVERTED_DATE, T1.FORECAST_FILE_ID, T1.FORECAST_CONSUMPTION
),
CTE_MPAN AS
(
SELECT T2.FORECAST_FILE_ID
,T2.MPAN_CORE
FROM CTE_CONS AS T1
LEFT JOIN dbo.ers_hh_forecast_file AS T2 ON T1.FORECAST_FILE_ID=T2.FORECAST_FILE_ID
),
CTE_GSP AS
(
SELECT T2.MPAN_CORE
,T2.GSP_GROUP_ID
FROM CTE_MPAN AS T1
LEFT JOIN dbo.ers_ed_supply_point AS T2 ON T1.MPAN_CORE=T2.MPAN_CORE
)
SELECT T1.CONVERTED_DATE
,T1.TOTAL
,T2.MPAN_CORE
,T1.TOTAL
FROM CTE_CONS AS T1
LEFT JOIN CTE_MPAN AS T2 ON T1.FORECAST_FILE_ID=T2.FORECAST_FILE_ID
LEFT JOIN CTE_GSP AS T3 ON T2.MPAN_CORE=T3.MPAN_CORE
由於表「ers_hh_forecast_consumption」有大量記錄,最好使用過濾器條件將所需記錄插入到臨時表中,並在CTE中使用該臨時表。 –
您是否有任何表的索引,例如預測消耗表的UTC_DATETIME索引。顯示錶格定義和索引將幫助你得到一個體面的答案。 –
當我們不知道存在哪些指標時,很難提供建議。同時,您可以使用SSMS查看查詢的執行計劃以確定優化。 – Greg