2012-11-01 124 views
-1

這是一個摘錄的SQL得到天oracle select語句重用?

AND S.Date   IN 

    (
    SELECT Date 
    FROM 
     (
     SELECT Date, 
     ROW_NUMBER() OVER (ORDER BY Date DESC)-1 Day 
     FROM CALENDAR_DIM 
     WHERE TYPE    = 'ABC' 
    ) 
    WHERE BUS_DAY BETWEEN 0 AND 2 
) 

我想在我的SQL兩個部分兩次運行此代碼。我怎麼能不粘貼相同的代碼。另外..我怎麼可以重寫上面的代碼?我有一些性能問題。

+0

爲什麼MySQL的標籤? –

+0

認爲你有一個錯字:不應該是'ROW_NUMBER()OVER(ORDER BY日期DESC)-1 BUS_DAY',或者我不知道你的BUS_DAY來自哪裏...... –

回答

3

解決方案1 ​​:使用WITH語句

WITH dateQuery AS (
    SELECT Date 
    FROM 
     (
     SELECT Date, 
     ROW_NUMBER() OVER (ORDER BY Date DESC)-1 BUS_DAY 
     FROM CALENDAR_DIM 
     WHERE TYPE = 'ABC' 
    ) 
    WHERE BUS_DAY BETWEEN 0 AND 2) 



SELECT xxx 
FROM yyy 
WHERE zzz 
AND s.Date IN (SELECT Date FROM dateQuery) 

唯一重複的部分是

SELECT Date FROM dateQuery 

解決方案2:創建一個視圖

CREATE OR REPLACE VIEW V_DATE_QUERY AS 
( SELECT Date 
    FROM 
     (
     SELECT Date, 
     ROW_NUMBER() OVER (ORDER BY Date DESC)-1 BUS_DAY 
     FROM CALENDAR_DIM 
     WHERE TYPE = 'ABC' 
    ) 
    WHERE BUS_DAY BETWEEN 0 AND 2) 

,並用同樣的方式

AND s.Date IN (Select Date FROM V_DATE_QUERY); 
+0

@ user648244,因爲它是一個「物化「子查詢(Oracle將其轉換爲內聯視圖或臨時表),而不僅僅是子查詢。 http://www.dba-oracle.com/t_with_clause.htm –

+0

是的,我發現謝謝你 – user648244

1

你會做這樣的view在數據庫中,像這樣:

CREATE VIEW view_date 
AS 
SELECT Date, 
    ROW_NUMBER() OVER (ORDER BY Date DESC)-1 Day 
FROM CALENDAR_DIM 
WHERE TYPE    = 'ABC' 

現在你可以使用:

AND S.Date   IN 

    (
    SELECT Date 
    FROM view_date 
    WHERE BUS_DAY BETWEEN 0 AND 2 
)