多字段统计并加上合计的取值问题!!!!!!(在线等)
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----fthreename----fthreecode----fqty-----fseqty
1241----www---------eee---------q111---------20010101-----22.4-----43.09
3345----www---------eee---------q111---------20010102-----44-------31.99
3166----www---------eee---------d222--------20010103-----21-------66
小计-----------------------------------107.72---186.39
3211----www---------dsdw--------ww1111--------30010101-----32.32----33.3
小计------------------------------------32.32----33.3
合计------------------------------------------------140.04---219.69
4677----aaa---------ooo---------s11111--------40010101------321------434
4696----aaa---------ooo---------s22222--------40010102------434------211
小计-------------------------------------755------645
5465----aaa---------rrr---------g11111--------50010101-------112------343
合计 -------------------------------------------------867------988
也就是按照fonename ftwoname分组算出合计,同时要获得fthreename,fthreecode三级名称和代码。
下面的可以实现fonename ftwoname的分组合计,不能获取到fthreename,fthreecode
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
怎么样才能取到fthreename,fthreecode的值呢?
------解决方案--------------------SQL code
楼上的思路真的不错。学习了。。
create table b(fid int,fonename varchar(50),ftwoname varchar(50),fqty numeric(8,2),fseqty numeric(8,2))
insert into b select 1241,'www','eee',22.4, 43.09
insert into b select 3345 , 'www' , 'eee' , 32, 44
insert into b select 3166 , 'www' , 'eee' , 21 , 66
insert into b select 3211 , 'www' , 'dsdw' , 32.32 , 33.3
insert into b select 4677 , 'aaa' , 'ooo' , 321 , 434
insert into b select 4696 , 'aaa' , 'ooo' , 434 , 211
insert into b select 5465 , 'aaa' , 'rrr' , 112 , 3432
select
fid,
[fonename1]=case when fid='' and fonename>'' then '小计' when fid=0 then ftwoname else fonename end ,
[ftwoname1]=case when fid='' then '' else ftwoname end,
fqty,
fseqty
from
(select * from b
union all
select '',f