數據分組問題

表:
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

*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章