oracle技术之group by rollup查询结构

在047考题中有以下这么一道考题

11.View the Exhibit and examine the descriptions of ORDER_ITEMS and ORDERS tables.

You want to display the CUSTOMER_ID, PRODUCT_ID, and total (UNIT_PRICE multiplied by

QUANTITY) for the order placed. You also want to display the subtotals for a CUSTOMER_ID as well as

for a PRODUCT_ID for the last six months.

Which SQL statement would you execute to get the desired output?

A. SELECT o.customer_id, oi.product_id, SUM(oi.unit_price*oi.quantity) "Total"

FROM order_items oi JOIN orders o

ON oi.order_id=o.order_id GROUP BY ROLLUP (o.customer_id,oi.product_id) WHERE MONTHS_BETWEEN(order_date, SYSDATE) <= 6;

B. SELECT o.customer_id, oi.product_id, SUM(oi.unit_price*oi.quantity) "Total"

FROM order_items oi JOIN orders o

ON oi.order_id=o.order_id GROUP BY ROLLUP (o.customer_id,oi.product_id) HAVING MONTHS_BETWEEN(order_date, SYSDATE) <= 6;

C. SELECT o.customer_id, oi.product_id, SUM(oi.unit_price*oi.quantity) "Total"

FROM order_items oi JOIN orders o

ON oi.order_id=o.order_id GROUP BY ROLLUP (o.customer_id, oi.product_id) WHERE MONTHS_BETWEEN(order_date, SYSDATE) >= 6;

D. SELECT o.customer_id, oi.product_id, SUM(oi.unit_price*oi.quantity) "Total"

FROM order_items oi JOIN orders o

ON oi.order_id=o.order_id WHERE MONTHS_BETWEEN(order_date, SYSDATE) <= 6 GROUP BY ROLLUP (o.customer_id, oi.product_id) ;


Answer: D

上面这道题中其实要选择正确的答案是很简单的,就是group by应该放在where的后面,但是题目中出现的一个知识点需要我们注意,就是rollup的使用。

大家都熟悉group by基本语法,例如要统计每个部门的员工最高的工资,就可以使用

select max(sal) from emp group by deptno;

但是如果出现比较复杂的统计,单单靠group by基本用法是不能满足的需求的,还得配合rollup一起来使用,例如:

需要安装职位,经理,部门来统计员工的总工资,并且对职位,经理做一个子统计

SQL> select job,mgr,deptno,sum(sal) from emp where deptno in(10,30) group by rollup(job,mgr,deptno);

JOB MGR DEPTNO SUM(SAL)

--------------------------- ---------- ---------- ----------

CLERK 7698 30 950

CLERK 7698 950

CLERK 7782 10 1300

CLERK 7782 1300

CLERK 2250

MANAGER 7839 10 2450

MANAGER 7839 30 2850

MANAGER 7839 5300

MANAGER 5300

SALESMAN 7698 30 5600

SALESMAN 7698 5600

JOB MGR DEPTNO SUM(SAL)

--------------------------- ---------- ---------- ----------

SALESMAN 5600

PRESIDENT 10 5000

PRESIDENT 5000

PRESIDENT 5000

18150

16 rows selected.

那么group by rollup的分组是按照以下步骤,在上述ROLLUP(job,mgr,deptno)例子中,首先会对(job,mgr,deptno)进行GROUP BY,然后对(job,mgr)进行GROUP BY,然后是(job)进行GROUP BY,最后对全表进行GROUP BY操作,结合上述的例子

首先对(job,mgr,deptno)分组,其统计结果类似如下:

CLERK 7698 30 950

然后对(job,mgr)分组,其统计结果类似如下:

CLERK 7698 950

然后对(job)分组,其统计结果类似如下:

CLERK 2250

最后对全表做一次分组统计

18150

这样分析以下,相信大家对group by rollup查询结构有一个全面的了解


oracle视频教程请关注:http://down.51cto.com/4202939/up


你可能感兴趣的:(rollup,by,group,查询结构,oracle技术)