按用户定义的日期分区sql

时间:2014-09-24 15:44:54

标签: sql

我有一张表,可以按天提供不同商品的单位销售额。我想总结一些用户定义的销售额(实际上是任意的,无法直接从数据中指定)。

我试图通过创建一个字段来指定是否在哪个句点日期之内,然后我可以按此分组。但是我的代码给了我错误" ORA-00923:FROM关键字找不到预期的位置"。

我的代码:

select
SUM(UNIT_SALES),
PERIOD =
    CASE 
             WHEN DAY_DATE >= TO_DATE('04/07/2013', 'DD/MM/YYYY') AND DAY_DATE <= TO_DATE('26/09/2013', 'DD/MM/YYYY') THEN 'Start of Period of pre_activity'
             WHEN DAY_DATE >= TO_DATE('27/09/2013', 'DD/MM/YYYY') AND DAY_DATE <= TO_DATE('01/04/2014', 'DD/MM/YYYY') THEN 'Start of Period of pre_activity'
             WHEN DAY_DATE >= TO_DATE('14/05/2014', 'DD/MM/YYYY') AND DAY_DATE <= TO_DATE('21/09/2014', 'DD/MM/YYYY') THEN 'Start of Period of pre_activity'
             ELSE 'NO PERIOD ASSIGNED'
    END
FROM MY_SALES_DAILY
GROUP BY PERIOD
ORDER BY PERIOD

如何在用户定义的时间段内实现此总和?

1 个答案:

答案 0 :(得分:0)

您的语法不正确。 PERIOD =不正确。请参阅下面更正的SQL。

select
SUM(UNIT_SALES),
    CASE 
             WHEN DAY_DATE >= TO_DATE('04/07/2013', 'DD/MM/YYYY') AND DAY_DATE <= TO_DATE('26/09/2013', 'DD/MM/YYYY') THEN 'Start of Period of pre_activity'
             WHEN DAY_DATE >= TO_DATE('27/09/2013', 'DD/MM/YYYY') AND DAY_DATE <= TO_DATE('01/04/2014', 'DD/MM/YYYY') THEN 'Start of Period of pre_activity'
             WHEN DAY_DATE >= TO_DATE('14/05/2014', 'DD/MM/YYYY') AND DAY_DATE <= TO_DATE('21/09/2014', 'DD/MM/YYYY') THEN 'Start of Period of pre_activity'
             ELSE 'NO PERIOD ASSIGNED'
    END AS PERIOD
FROM DW_MASTER_SALES_DAILY
GROUP BY     CASE 
             WHEN DAY_DATE >= TO_DATE('04/07/2013', 'DD/MM/YYYY') AND DAY_DATE <= TO_DATE('26/09/2013', 'DD/MM/YYYY') THEN 'Start of Period of pre_activity'
             WHEN DAY_DATE >= TO_DATE('27/09/2013', 'DD/MM/YYYY') AND DAY_DATE <= TO_DATE('01/04/2014', 'DD/MM/YYYY') THEN 'Start of Period of pre_activity'
             WHEN DAY_DATE >= TO_DATE('14/05/2014', 'DD/MM/YYYY') AND DAY_DATE <= TO_DATE('21/09/2014', 'DD/MM/YYYY') THEN 'Start of Period of pre_activity'
             ELSE 'NO PERIOD ASSIGNED'
             END
ORDER BY PERIOD