效果如圖所示:

測(cè)試sql語(yǔ)句如下:
復(fù)制代碼 代碼如下:
declare @tab table(Class varchar(20),Student varchar(20),Course varchar(50),Quantity decimal(7,2));
insert into @tab(Class,Student,Course,Quantity) values('A班','張三','語(yǔ)文',60);
insert into @tab(Class,Student,Course,Quantity) values('A班','張三','數(shù)學(xué)',70);
insert into @tab(Class,Student,Course,Quantity) values('A班','張三','英語(yǔ)',80);
insert into @tab(Class,Student,Course,Quantity) values('A班','李四','語(yǔ)文',30);
insert into @tab(Class,Student,Course,Quantity) values('A班','李四','數(shù)學(xué)',40);
insert into @tab(Class,Student,Course,Quantity) values('A班','李四','英語(yǔ)',50);
insert into @tab(Class,Student,Course,Quantity) values('B班','王五','語(yǔ)文',65);
insert into @tab(Class,Student,Course,Quantity) values('B班','王五','數(shù)學(xué)',75);
insert into @tab(Class,Student,Course,Quantity) values('B班','王五','英語(yǔ)',85);
insert into @tab(Class,Student,Course,Quantity) values('B班','趙六','語(yǔ)文',35);
insert into @tab(Class,Student,Course,Quantity) values('B班','趙六','數(shù)學(xué)',45);
insert into @tab(Class,Student,Course,Quantity) values('B班','趙六','英語(yǔ)',55);
select * from @tab
select
(case when Grouping(Class)=1 then '總平均' when Grouping(Student)=1 then '' else Class end ) as Class
,(case when Grouping(Class)=1 then '' when Grouping(Student)=1 then '平均' else Student end) as Student
,avg(語(yǔ)文) as 語(yǔ)文
,avg(數(shù)學(xué)) as 數(shù)學(xué)
,avg(英語(yǔ)) as 英語(yǔ)
,avg(總分) as 總分
from (
select Class,Student
,(select isnull(sum(Quantity),0) from @tab where Class=t.Class and Student=t.Student and Course='語(yǔ)文') as '語(yǔ)文'
,(select isnull(sum(Quantity),0) from @tab where Class=t.Class and Student=t.Student and Course='數(shù)學(xué)') as '數(shù)學(xué)'
,(select isnull(sum(Quantity),0) from @tab where Class=t.Class and Student=t.Student and Course='英語(yǔ)') as '英語(yǔ)'
,(select isnull(sum(Quantity),0) from @tab where Class=t.Class and Student=t.Student) as '總分'
from @tab as t
group by Class,Student
) as tempTab
group by Class,Student,語(yǔ)文,數(shù)學(xué),英語(yǔ),總分 with rollup
having Grouping(語(yǔ)文)=1
and Grouping(數(shù)學(xué))=1
and Grouping(英語(yǔ))=1
您可能感興趣的文章:- sql分組后二次匯總(處理表重復(fù)記錄查詢(xún)和刪除)的實(shí)現(xiàn)方法
- SQL SERVER 分組求和sql語(yǔ)句
- 顯示同一分組中的其他元素的sql語(yǔ)句
- sql獲取分組排序后數(shù)據(jù)的腳本
- SQL進(jìn)行排序、分組、統(tǒng)計(jì)的10個(gè)新技巧分享
- SQL分組排序去重復(fù)的小實(shí)例
- 以數(shù)據(jù)庫(kù)字段分組顯示數(shù)據(jù)的sql語(yǔ)句(詳細(xì)介紹)
- SQL中Group分組獲取Top N方法實(shí)現(xiàn)可首選row_number
- Sql Server:多行合并成一行,并做分組統(tǒng)計(jì)的兩個(gè)方法
- Sql Server 分組統(tǒng)計(jì)并合計(jì)總數(shù)及WITH ROLLUP應(yīng)用
- SQL語(yǔ)句分組獲取記錄的第一條數(shù)據(jù)的方法
- sqlserver巧用row_number和partition by分組取top數(shù)據(jù)
- sql 分組查詢(xún)問(wèn)題
- SQLserver 實(shí)現(xiàn)分組統(tǒng)計(jì)查詢(xún)(按月、小時(shí)分組)
- 分組后分組合計(jì)以及總計(jì)SQL語(yǔ)句(稍微整理了一下)