2017-03-07 99 views
0

有沒有什麼辦法可以改善下面的查詢?在sql查詢中加入聯合查詢查殺性能

下面的查詢給出了正確的結果,但是會影響性能。

+0

每個單獨的查詢是否也慢?你有ID列的索引嗎?順便說一句,我認爲你需要使用PIVOT而不是寫這樣的查詢。 – FLICKER

+0

您應該從ID開始,如果您不希望table1和table2之間有重複的ID,您可以用Union全部替換Union – NotCaring

+0

@ FLICKER:謝謝。我有一個ID的索引。是否可以通過樞軸。好心建議 –

回答

2

也許這樣?

Select 
    ID, 
    max(case when MYDATE = '20160105 10:00:00' then PRICE else 0 end), 
    max(case when MYDATE = '20140805 10:00:00' then PRICE else 0 end), 
    max(case when MYDATE = '20170215 10:00:00' then PRICE else 0 end) 
FROM 
(
    select ID, PRICE FROM TABLE1 WHERE MYDATE in ('20160105 10:00:00', '20140805 10:00:00', '20170215 10:00:00') 
    UNION ALL 
    SELECT ID, PRICE FROM TABLE2 WHERE MYDATE in ('20160105 10:00:00', '20140805 10:00:00', '20170215 10:00:00') 
) A 
group by ID 

猜測會更容易些,如果你提供的任何例子...

+2

也許切換到'union all'來避免重複數據刪除? – SqlZim

+0

是的,這可能是可能的,當然取決於數據是什麼 –

+0

是真的,但因爲你正在彙總和使用'max()'無論如何... – SqlZim

0

你可以避開(),使用A.ID的加入,這可能會產生一些好處的性能

Select A.ID, A.[2016 Price], B.[2014 Price], C.[2017 Price] 
FROM 

    (
    select ID, PRICE [2016 Price] FROM TABLE1 WHERE MYDATE = 2016-01-05 10:00:00 
    UNION 
    SELECT ID, PRICE FROM TABLE2 WHERE MYDATE = 2016-01-05 10:00:00 
) A 

INNER JOIN 

    (
    select ID, PRICE [2014 Price] FROM TABLE1 WHERE MYDATE = 2014-08-05 10:00:00 
    UNION 
    SELECT ID, PRICE FROM TABLE2 WHERE MYDATE = 2014-08-05 10:00:00 
) B ON A.ID =B.ID 

INNER JOIN 

    (
    select ID, PRICE [2017 Price] FROM TABLE1 WHERE MYDATE = 2017-02-15 10:00:00 
    UNION 
    SELECT ID, PRICE FROM TABLE2 WHERE MYDATE = 2017-02-15 10:00:00 
) ON A.ID =C.ID