日期:2014-05-17  浏览次数:20699 次

求个pl/sql的例子
求个像这样的例子

name price num type
篮球 20 2 1
足球 10 3 1
羽毛球 5 10 1
白衣 28 1 2
红衣 32 3 2
黑衣 30 1 2
输出

type name totalprice
----- ----- ---------
 1 篮球 40
-----------------------------
  足球 30
-----------------------------
  羽毛球 50
-----------------------------
  total 120

 2 白衣 28
-----------------------------
  红衣 96
-----------------------------
  黑衣 30
-----------------------------
  total 154 
怎么写,求语句

------解决方案--------------------
SQL code
with temp as (
select '篮球' name,20 price,2 num,1 type from dual
union all
select '足球' name,10 price,3 num,1 type from dual
union all
select '羽毛球' name,5 price,10 num,1 type from dual
union all
select '白衣' name,28 price,1 num,2 type from dual
union all
select '红衣' name,32 price,3 num,2 type from dual
union all
select '黑衣' name,30 price,1 num,2 type from dual
)
select type,name,sum(price*num) totalprice from temp   group by rollup(type,name) order by type

------解决方案--------------------
这样可以么?
SQL code

create table t1 (name varchar2(10), price number(10,2), num number(5), type varchar2(5));

insert into t1 values ('篮球', 20,2,1);
insert into t1 values ('足球', 10,3,1);
insert into t1 values ('羽毛球', 5,10,1);
insert into t1 values ('白衣', 28,1,2);
insert into t1 values ('红衣', 32,3,2); 
insert into t1 values ('黑衣', 30,1,2);
commit;

select type,nvl(name,'合计') name,sum(price*num) t_price
from t1
group by rollup(type,name)

    type    name    t_price
-----------------------------------
1    1    篮球    40
2    1    足球    30
3    1    羽毛球    50
4    1    合计    120
5    2    白衣    28
6    2    黑衣    30
7    2    红衣    96
8    2    合计    154
9        合计    274

------解决方案--------------------
--name price num type
with t as (
select '篮球' as fname, 20 as price, 2 as num, 1 as ftype from dual
union all
select '足球', 10, 3, 1 from dual
union all
select '羽毛球', 5, 10, 1 from dual
union all
select '白衣', 28, 1, 2 from dual
union all
select '红衣', 32, 3, 2 from dual
union all
select '黑衣', 30, 1, 2 from dual
)
select ftype,nvl(fname,'total(' || case when grouping(ftype)=0 then to_char(ftype) else 'all' end || '):') as fname,sum(price) as totalprice from t
group by rollup(ftype,fname) 

--结果
FTYPE FNAME TOTALPRICE
---------------------- ------------------------------------------------ ---------------------- 
1 篮球 20
1 足球 10
1 羽毛球 5
1 total(1): 35
2 白衣 28
2 红衣 32
2 黑衣 30
2 total(2): 90
total(all): 125
------解决方案--------------------