数据分组问题

表:
F1       F2
-----------------
A         1    
A         1    
A         1    
A         2    
A         1    
B         1    
B         1    
B         1  
请问怎样实现如下结果(SQL解决):
F1        F2     
-----------------
A         1     
A         1     
A         1     
A         2     
A         1
 Total A: 6 
B         1     
B         1     
B         1     
 Total B: 3  

--数据
declare @t table (F1 varchar(10),F2 int)
insert @t select 'A',1
union all select 'A',1
union all select 'A',1
union all select 'A',2
union all select 'A',1
union all select 'B',1
union all select 'B',1
union all select 'B',1
union all select 'C',1
union all select 'C',2
union all select 'C',1
union all select 'C',3

--语句1.不显示最后一行(如果不要的话)

declare @count int
declare @s varchar(8000)
select id=identity(int,1,1), * into # from @t
set @count=@@rowcount+(select count(distinct(F1)) from #)
select @count
select  @s=(
'select top '+rtrim(@count)+'
(
case isnumeric(isnull(rtrim(id),''Total:'')) when 1 then ''''
when 0  then (isnull(rtrim(id),''Total:'')) end
)+isnull(F1,''All'') as F1
,sum(F2) as F2
from #
group by F1,id with rollup
')
exec (@s)

--语句2,显示最后一行
select
(
case isnumeric(isnull(rtrim(id),'Total:')) when 1 then ''
when 0  then (isnull(rtrim(id),'Total:')) end
)+isnull(F1,'All') as F1
,sum(F2) as F2
from #
group by F1,id with rollup

--破弃测试环境
drop table #

/*
结果集1:

F1                     F2         
---------------------- -----------
A                      1
A                      1
A                      1
A                      2
A                      1
Total:A                6
B                      1
B                      1
B                      1
Total:B                3
C                      1
C                      2
C                      1
C                      3
Total:C                7

结果集2
F1                     F2         
---------------------- -----------
A                      1
A                      1
A                      1
A                      2
A                      1
Total:A                6
B                      1
B                      1
B                      1
Total:B                3
C                      1
C                      2
C                      1
C                      3
Total:C                7
Total:All              16

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值