2016-05-16 56 views
0

我有一個SQL查詢,它在UNION ALL查詢的每個時間窗口內從每天獲取幾個數據點,然後在結果集中爲每一天求和該數據。獲取來自UNION ALL結果集的總和

我想添加到結果集中的總數是結果集中所有日子的底部總數。我試圖使用ROLLUP(與GRO​​UP BY語句)沒有成功,並且我不斷收到錯誤ORA-00933: SQL command not properly ended

不知道是否有一個竅門,如果根本不起作用的話,可以使用UNION ALL進行ROLLUP。我也嘗試了一個臨時表,然後使用臨時表的總和來執行一個UNION ALL,但是這看起來很複雜(並且我還沒有能夠使它工作)。

有人可以幫助指導我嗎?這裏是我的工作代碼:

SELECT /*+ USE_HASH(x) */ 
ACTIVITY_DAY 
, SUM(ORDERED_UNITS) 
, SUM(ORDERED_AMT) 
FROM (
    SELECT ACTIVITY_DAY,ORDERED_UNITS,ORDERED_AMT FROM D_DAILY_ORDERS 
     WHERE REGION_ID = 1 
     AND MARKETPLACE_ID = 1 
     AND ACTIVITY_DAY BETWEEN TO_DATE('20160409','YYYYMMDD') AND TO_DATE('20160505','YYYYMMDD') 
     AND ID IN ('B019433MGC', 'B019433O4C', 'B00STUX0F0', 'B017SL40S6', 'B00ZHJDJ5W', 'B00STUX276', 'B017SL44RI', 'B00ST415S0', 'B00ST414O0') 
    UNION ALL 
    SELECT ACTIVITY_DAY,ORDERED_UNITS,ORDERED_AMT FROM D_DAILY_ORDERS 
     WHERE REGION_ID = 1 
     AND MARKETPLACE_ID = 1 
     AND ACTIVITY_DAY BETWEEN TO_DATE('20160501','YYYYMMDD') AND TO_DATE('20160505','YYYYMMDD') 
     AND ID IN ('B007V4YR5M', 'B00BHQ9CHI') 
) x 
GROUP BY ACTIVITY_DAY 
ORDER BY ACTIVITY_DAY 
; 
+0

我相信'rollup'是正確的方式;你只需使用'GROUP BY ROLLUP(ACTIVITY_DAY)'。你可以請張貼錯誤的查詢? – Aleksej

+0

什麼是彙總查詢版本引發該錯誤? –

回答

0

如果我理解的很好,ROLLUP是正確的方法;你可能有一些語法錯誤:

SQL> SELECT 
    2 ACTIVITY_DAY 
    3 , SUM(ORDERED_UNITS) 
    4 , SUM(ORDERED_AMT) 
    5 FROM (
    6  select sysdate as ACTIVITY_DAY, 1 as ORDERED_UNITS, 10 as ORDERED_AMT from dual union all 
    7  select sysdate-1 as ACTIVITY_DAY, 2 as ORDERED_UNITS, 20 as ORDERED_AMT from dual union all 
    8  select sysdate-1 as ACTIVITY_DAY, 2 as ORDERED_UNITS, 20 as ORDERED_AMT from dual 
    9 ) x 
10 GROUP BY rollup(ACTIVITY_DAY) 
11 ORDER BY ACTIVITY_DAY 
12 ; 

ACTIVITY_ SUM(ORDERED_UNITS) SUM(ORDERED_AMT) 
--------- ------------------ ---------------- 
15-MAG-16     4    40 
16-MAG-16     1    10 
          5    50