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

高手进,看看一条语句能否解决?
Type的取值

Type valude
1 A业务
2 B业务
3 C业务

表中的数据为:
name Code Type fee1 fee2 fee3
公司1 06766100063 1 20.00 30.00 40.00
公司2 06066 1 30.00 20.00 10.00
公司3 040506 2 10.00 20.00 30.00
公司4 09981 2 10.00 10.00 10.00
公司5 075523 3 20.00 20.00 20.00
公司6 06766010170 3 20.00 20.00 20.00

能否用一条SQL搞定?group   by   rollup   or   grouping

name Code Type fee1 fee2 fee3
公司1 06766100063 1 20.00 30.00 40.00
公司2 06066 1 30.00 20.00 10.00
A业务小计   小计 50.00 50.00 50.00
公司3 040506 2 10.00 20.00 30.00
公司4 09981 2 10.00 10.00 10.00
B业务 小计 20.00 30.00 40.00
公司5 075523 3 20.00 20.00 20.00
公司6 06766010170 3 20.00 20.00 20.00
C业务小计   小计 40.00 40.00 40.00
所有业务总计   总计 110.00 120.00 130.00

------解决方案--------------------
A业务 小计 1 50 50 50
公司1 06766100063 1 20 30 40
公司2 06066 1 30 20 10
B业务 小计 2 20 30 40
公司4 09981 2 10 10 10
公司3 040506 2 10 20 30
C业务 小计 3 40 40 40
公司5 075523 3 20 20 20
公司6 06766010170 3 20 20 20
所有业务总计 总计 110 120 130

------解决方案--------------------
select * from (
select * from tb
union
select a.valude,b.* from
( select '小计 ' code,type,sum(fee1) fee1,sum(fee2) fee2,sum(fee3) fee3 from tb group by type ) b
left join ta a on a.type=b.type
Union
select '所有业务总计 ' name , '总计 ' code,null type,sum(fee1) fee1,sum(fee2) fee2,sum(fee3) fee3 from tb
) order by type ,fee1

------解决方案--------------------
select nvl(name,decode(Type,1, 'A業務 ',2, 'B業務 ',3, 'C業務 ', '合計 ')),
decode(nvl(name,0),0,decode(nvl(Type,0),0, '合計 ', '小計 ',max(code)),
decode(nvl(name,0),0, ' ',to_char(Type)),
sum(fee1),sum(fee2),sum(fee3)
group by rollup(Type,name)
------解决方案--------------------
sql server 下測試
==============================================


declare @tt table(name varchar(20),Code varchar(50),Type int,fee1 float,fee2 float,fee3 float)
insert into @tt
select '公司1 ', '06766100063 ', 1 ,20.00, 30.00 ,40.00 union all
select '公司2 ', '06066 ', 1 ,30.00, 20.00, 10.00 union all
select '公司3 ', '040506 ', 2, 10.00, 20.00, 30.00 union all
select '公司4 ', '09981 ', 2 ,10.00, 10.00, 10.00 union all
select '公司5 ', '075523 ', 3, 20.00, 20.00, 20.00 union all
select '公司6 ', '06766010170 ' ,3, 20.00, 20.00, 20.00


select isnull(name,case when Type=1 then 'A ' when Type=2 then 'B ' when Type=3 then 'C ' else '合計 ' end),
case when isnull(name, ' ')= ' ' then
case when isnull(Type, ' ')= ' ' then '合計 ' else '小計 ' end else max(Code) end,
case when isnull(name, ' ')= ' ' then ' ' else cast(Type as varchar(2)) end ,sum(fee1),sum(fee2),sum(fee3)
from @tt
group by Type,[name] with rollup


==============================
公司1 06766100063 1 20.0 30.0 40.0
公司2 06066 1 30.0 20.0 10.0
A 小計 50.0 50.0 50.0
公司3 040506 2 10.0 20.0 30.0
公司4 09981 2 10.0 10.0 10.0
B 小計 20.0 30.0 40.0
公司5 075523 3 20.0 20.0 20.0
公司6 06766010170 3 20.0 20.0 20.0
C 小計 40.0 40.0 40.0
合計 合計 110.0 120.0 130.0

------解决方案--------------------