我需要重寫一個不包含彙總函數的簡單查詢。你可以幫幫我嗎?Oracle:將查詢中的「彙總」替換爲其他內容
這是一個原始查詢:
SELECT e.department_id,
e.job_id,
SUM(e.salary)
FROM EMPLOYEES e
GROUP BY ROLLUP(e.department_id, e.job_id);
我想有可能使用UNION語句改寫,啊?
我需要重寫一個不包含彙總函數的簡單查詢。你可以幫幫我嗎?Oracle:將查詢中的「彙總」替換爲其他內容
這是一個原始查詢:
SELECT e.department_id,
e.job_id,
SUM(e.salary)
FROM EMPLOYEES e
GROUP BY ROLLUP(e.department_id, e.job_id);
我想有可能使用UNION語句改寫,啊?
以下應該會返回與彙總相同的結果,但性能較差,對「級別」的控制較少。
select e.department_id
,e.job_id
,SUM(e.salary)
from EMPLOYEES e
group
by e.department_id
,e.job_id
union all
select e.department_id
,null
,SUM(e.salary)
from EMPLOYEES e
group
by e.department_id
union all
select null
,null
,SUM(e.salary)
from EMPLOYEES e;
你可以使用一個CTE來處理它(注意我通過連接創建了EMPLOYEE表,只是爲了獲得示例數據)。有可能有更好的方法來做到這一點,但這是一種方式!
WITH EMPLOYEES AS(
SELECT MOD(LEVEL,5) DEPARTMENT_ID
, LEVEL JOB_ID
, 1000*LEVEL SALARY
FROM DUAL
CONNECT BY LEVEL < 10
)
, SUMMEDDATA AS(
SELECT e.department_id,
e.job_id,
SUM(e.salary) SUMMED_SALARY
FROM EMPLOYEES e
GROUP BY e.department_id, e.job_id
)
, SUMMEDJOB_ID AS(
SELECT e.department_id,
SUM(e.salary) SUMMED_SALARY
FROM EMPLOYEES e
GROUP BY e.department_id
)
, SUMMEDTOTAL AS(
SELECT
SUM(e.salary) SUMMED_SALARY
FROM EMPLOYEES e
)
SELECT DEPARTMENT_ID ,
JOB_ID ,
SUMMED_SALARY
FROM SUMMEDDATA
UNION ALL
SELECT DEPARTMENT_ID ,
NULL ,
SUMMED_SALARY
FROM SUMMEDJOB_ID
UNION ALL
SELECT NULL ,
NULL ,
SUMMED_SALARY
FROM SUMMEDTOTAL
ORDER BY 1 NULLS LAST, 2 NULLS LAST ;
DEPARTMENT_ID JOB_ID SUMMED_SALARY
---------------------- ---------------------- ----------------------
0 5 5000
0 5000
1 1 1000
1 6 6000
1 7000
2 2 2000
2 7 7000
2 9000
3 3 3000
3 8 8000
3 11000
4 4 4000
4 9 9000
4 13000
45000
不需要一個UNION,你可以使用GROUPING SETS。這將產生相同的結果,甚至相同的解釋計劃:
SELECT e.department_id,
e.job_id,
SUM(e.salary)
FROM EMPLOYEES e
GROUP BY GROUPING SETS((e.department_id, e.job_id), (e.department_id),())
我的問題是,我沒有在我的電腦上安裝oracle,我無法「嘗試」某些東西。 – user628913 2011-02-22 19:08:53
那麼你如何期待確定答案是否有效? Oracle Express是免費的(目前是10g,IIRC)。 – 2011-02-22 19:20:02
家庭作業? – tbone 2011-02-22 20:50:54