oracle select语句重用?

时间:2012-11-01 09:36:09

标签: mysql database oracle select

这是一个提取日期的提取sql

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的两个部分中运行此代码两次。如果不粘贴相同的代码,我怎么能这样做。另外..我怎么能重写上面的代码?我在性能方面遇到了一些问题。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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
  )