有没有办法在PL / SQL SELECT中声明日期变量

时间:2016-05-04 00:00:07

标签: sql date plsql subquery

我正在使用多个子查询从同一个表中提取多个日期范围的数据。有没有办法设置日期变量,所以我不必连续编辑日期范围?

例如:

Select A.Name,
    ,CASE
    WHEN B.WK1 IS NULL
    THEN 0
    ELSE B.WK1
    END as WK1

    ,CASE
    WHEN C.WK2 IS NULL
    THEN 0
    ELSE C.WK2
    END AS WK2

FROM

    (SELECT DISTINCT NAME
    FROM NAMES) A

    RIGHT OUTER JOIN
    (SELECT NAME,
    SUM(SALES) as WK1

    FROM SALES
    WHERE DATE between 1-JAN-2000 and 7-JAN-2000
    GROUP BY NAME) B
    ON NAME

    RIGHT OUTER JOIN
    (SELECT NAME,
    SUM(SALES) as WK2

    FROM SALES
    WHERE DATE between 8-JAN-2000 and 15-JAN-2000
    GROUP BY NAME) C
    ON NAME

基本上我要做的是从一个日期开始滚动多周。

1 个答案:

答案 0 :(得分:0)

只需用绑定变量(例如:date1)替换Date值,如下所示。第一次运行查询时Toad将询问您这些变量的值。之后Toad会记住您输入的值,因此它将预先填充相同的值,因此您不必再次键入它们。您还需要确保选择正确的数据类型。

Select A.Name,
    ,CASE
    WHEN B.WK1 IS NULL
    THEN 0
    ELSE B.WK1
    END as WK1

    ,CASE
    WHEN C.WK2 IS NULL
    THEN 0
    ELSE C.WK2
    END AS WK2

FROM

    (SELECT DISTINCT NAME
    FROM NAMES) A

    RIGHT OUTER JOIN
    (SELECT NAME,
    SUM(SALES) as WK1

    FROM SALES
    WHERE DATE between :date1 and :date2
    GROUP BY NAME) B
    ON NAME

    RIGHT OUTER JOIN
    (SELECT NAME,
    SUM(SALES) as WK2

    FROM SALES
    WHERE DATE between :date3 and :date4
    GROUP BY NAME) C
    ON NAME