Oracle表的常用查询实验(七)
1.问题描述:
有一个商品信息表,该表反应了各种商品的销售情况,一个产品是按照gid和gname两个字段来区分的,一个产品可能会有多个型号。
create table T_Goods
(
Id int primary key,
GId varchar2(10) not null,
GName varchar2(20) not null,
GColour varchar2(10),
GWithin int,
GSize varchar2(10),
GNumber int
)
CREATE SEQUENCE seq_goods
INCREMENT BY 1
START WITH 1
NOMAXVALUE
NOCYCLE
CACHE 10;
现要将各种商品各种型号的销售情况进行汇总统计,达到如下效果:
2.需求分析:
分类统计--->说明要用到group by 和sum()函数
group by 分两种情况:(1)group by GId, gname, gcolour, gwithin, gsize 得到的是每种型号的销售量
(2)group by gid, gname 得到的是每种产品的销售量
3.解答过程:
(1)求每种型号的销售量
(2)求每种产品的销售量
(3)求商品的总销售量
(4)将以上3个结果集联合在一起
(5)用decode()函数精简gid和gname,用row_number() over(partition by ) 函数来排序
4.SQL代码:
select rownum seq,
decode(rn, 1, gid) gid,
decode(rn, 1, gname) gname,
gcolour,
gwithin,
gsize,
gnumber
from (select t.*, row_number() over(partition by gid,gname order by gnumber) rn
from (select GId,
gname,
gcolour,
gwithin,
gsize,
sum(gnumber) gnumber
from t_goods
group by GId, gname, gcolour, gwithin, gsize
union all
select gid, gname, null, null, '小计', sum(gnumber)
from t_goods
group by gid, gname
union all
select null, null, null, null, '总计', sum(gnumber)
from t_goods) t);