我正在嘗試創建視圖,但從此視圖中選擇語句需要超過15秒。如何使其更快。我對該視圖的查詢如下。創建視圖,SQL查詢性能
create view Summary as
select distinct A.Process_date,A.SN,A.New,A.Processing,
COUNT(case when B.type='Sold' and A.status='Processing' then 1 end) as Sold,
COUNT(case when B.type='Repaired' and A.status='Processing' then 1 end) as Repaired,
COUNT(case when B.type='Returned' and A.status='Processing' then 1 end) as Returned
from
(select distinct M.Process_date,M.SN,max(P.enter_date) as enter_date,M.status,
COUNT(case when M.status='New' then 1 end) as New,
COUNT(case when M.status='Processing' and P.cn is null then 1 end) as Processing
from DB1.dbo.Item_details M
left outer join DB2.dbo.track_data P on M.SN=P.SN
group by M.Process_date,M.SN,M.status) A
left outer join DB2.dbo.track_data B on A.SN=B.SN
where A.enter_date=B.enter_date or A.enter_date is null
group by A.Process_date,A.New,A.Processing,A.SN
這view..my選擇查詢後
select distinct process_date,sum(New),sum(Processing),sum(sold),sum(repaired),sum(returned) from Summary where month(process_date)=03 and year(process_date)=2011
請建議我什麼改變來進行的查詢執行得更快。
謝謝 ARB
重複使用'select distinct ...'是第一個跡象表明一切都不好 - 如果你得到重複的行,爲什麼?以合理的方式消除重複,而不是像「select distinct ...」那樣使用創可貼是首先要解決的問題。 –
'Distinct'不是爲你做任何事情,'組by'已經使結果不同。可能不會加速任何東西,因爲查詢優化器會知道,不同的是多餘的,但沒有額外的關鍵字視圖定義會更清晰。 –