求大侠们,这样的分级汇总怎么做!!!
有如下表:
列1 列2 列3 列4
1001.001 A B 3
1001.002 C D 4
1001.003.001 E F 5
1001.003.002 G H 3
求如下结果:
列1 列2 列3 列4
1001.001 A B 3
1001.002 C D 4
1001.003.001 E F 5
1001.003.002 G H 3
1001.003 小计 8
1001 合计 15
注:其中列1的级次下还有很多明细的级次.比如:1001.003.001.001
求它的一个分级汇总.
[解决办法]
下面通过函数来实现:
--1.函数
if exists(select * from sys.objects where name = 'f_splitSTR' and type = 'tf')
drop function dbo.f_splitSTR
go
create function dbo.f_splitSTR
(
@s varchar(8000), --要分拆的字符串
@split varchar(10) --分隔字符
)
returns @re table( --要返回的临时表
id int,
col varchar(1000) --临时表中的列
)
as
begin
declare @len int
declare @temp_str varchar(100)
declare @i int;
set @temp_str = ''
set @i = 0;
set @len = LEN(@split) --分隔符不一定就是一个字符,可能是2个字符
while CHARINDEX(@split,@s) >0
begin
set @i = @i + 1
if @i = 1
set @temp_str = @temp_str + left(@s,charindex(@split,@s) - 1)
else
set @temp_str = @temp_str + @split + left(@s,charindex(@split,@s) - 1)
insert into @re
values(@i,@temp_str);
set @s = STUFF(@s,1,charindex(@split,@s) - 1 + @len ,'') --覆盖:字符串以及分隔符
end
insert into @re values(@i+1,@temp_str+@split+@s)
return --返回临时表
end
go
drop table tb
go
create table tb
(
列1 varchar(20),
列2 varchar(20),
列3 varchar(20),
列4 int
)
insert into tb
select '1001.001' , 'A' , 'B' , 3
union all select '1001.002' , 'C', 'D' , 4
union all select '1001.003.001', 'E', 'F' , 5
union all select '1001.003.002', 'G', 'H' , 3
go
;with t
as
(
select tb.*,
col,
ID,
case when col = 列1 then 1 else 0 end as flag
from tb
cross apply dbo.f_splitSTR(列1,'.')
)
select col,case when id = 1 and flag = 0 then '总计'
else t2.列2
end as 列2,
case when id = 2 and flag = 0 then '小计'
else t2.列3
end as 列3,
t1.列4
from
(
select col,flag,id ,SUM(列4) as 列4
from t
group by col,flag,id
)t1
left join tb t2
on t2.列1 = t1.col
order by flag desc,len(col) desc
/*
col 列2列3 列4
1001.003.001EF 5
1001.003.002GH 3
1001.001 AB 3
1001.002 CD 4
1001.003 NULL小计 8
1001 总计NULL 15
*/