日期:2014-05-18  浏览次数:20607 次

关于多字段统计并加上合计的问题!!!!!!(在线等)

fid fonename ftwoname fqty fseqty
1241 www eee 22.4 43.09
3345 www eee 32 44
3166 www eee 21 66
3211 www dsdw 32.32 33.3
4677 aaa ooo 321 434
4696 aaa ooo 434 211
5465 aaa rrr 112 3432

能不能将fonename 和 ftwoname统计结果插入到该表中呢?要实现的结果表如下:
fid fonename ftwoname fqty fseqty
1241 www eee 22.4 43.09
3345 www eee 32 44
3166 www eee 21 66
  小计 107.72 186.39
3211 www dsdw 32.32 33.3
  小计 32.32 33.3
  合计 140.04 219.69
4677 aaa ooo 321 434
4696 aaa ooo 434 211
  小计 755 645
5465 aaa rrr 112 343
  合计 867 988

怎么实现这个亚?


------解决方案--------------------
create table #表(fid int,fonename varchar(20),ftwoname varchar(20),fqty numeric(8,2),fseqty numeric(8,2)) 
insert #表 select
1241,'www','eee', 22.4, 43.09 insert #表 select 
3345,'www','eee', 32, 44 insert #表 select
3166,'www','eee', 21, 66 insert #表 select
3211,'www','dsdw',32.32,33.3 insert #表 select
4677,'aaa','ooo', 321, 434 insert #表 select
4696,'aaa','ooo', 434, 211 insert #表 select
5465,'aaa','rrr', 112, 3432 

select fid,(case when ftwoname is null and fonename is not null then '' else isnull(fonename,'合计')end) fonename,
(case when fonename is null then '' else isnull(ftwoname,'小计') end)ftwoname,sum(fqty) fqty,sum(fseqty) fseqty 
from #表 group by fonename,ftwoname,fid with rollup 
-----------------
4677 aaa ooo 321.00 434.00
4696 aaa ooo 434.00 211.00
NULL aaa ooo 755.00 645.00
5465 aaa rrr 112.00 3432.00
NULL aaa rrr 112.00 3432.00
NULL 小计 867.00 4077.00
3211 www dsdw 32.32 33.30
NULL www dsdw 32.32 33.30
1241 www eee 22.40 43.09
3166 www eee 21.00 66.00
3345 www eee 32.00 44.00
NULL www eee 75.40 153.09
NULL 小计 107.72 186.39
NULL 合计 974.72 4263.39

------解决方案--------------------
declare @a table(fid varchar(20), fonename varchar(20), ftwoname varchar(20), fqty decimal(20,2), fseqty decimal(20,2))
insert @a select '1241', 'www', 'eee', 22.4, 43.09 
union all select '3345' ,'www' ,'eee', 32, 44 
union all select '3166' ,'www' ,'eee', 21, 66 
union all select '3211' ,'www' ,'dsdw', 32.32, 33.3 
union all select '4677' ,'aaa' ,'ooo', 321, 434 
union all select '4696' ,'aaa' ,'ooo', 434, 211 
union all select '5465' ,'aaa' ,'rrr', 112, 343 

select case when fonename is null and ftwoname is null then '总计' else isnull(fid,'') end fid,
case when fonename is null and ftwoname is null then '' 
when fid is null and ftwoname is null then '合计' 
when fid is null then '' else fonename end fonename,
case when fid is null and ftwoname is null then ''
when fid is null then '小计' else ftwoname end ftwoname,sum(fqty)fqty,sum(fseqty)fseqty
from @a
group by fonename,ftwoname,fid with rollup