一句Sql把縱向表轉(zhuǎn)為橫向表,并分別分組求平均和總平均值
發(fā)布日期:2022-01-28 19:14 | 文章來源:gibhub

測試sql語句如下:
復(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班','張三','語文',60);
insert into @tab(Class,Student,Course,Quantity) values('A班','張三','數(shù)學(xué)',70);
insert into @tab(Class,Student,Course,Quantity) values('A班','張三','英語',80);
insert into @tab(Class,Student,Course,Quantity) values('A班','李四','語文',30);
insert into @tab(Class,Student,Course,Quantity) values('A班','李四','數(shù)學(xué)',40);
insert into @tab(Class,Student,Course,Quantity) values('A班','李四','英語',50); insert into @tab(Class,Student,Course,Quantity) values('B班','王五','語文',65);
insert into @tab(Class,Student,Course,Quantity) values('B班','王五','數(shù)學(xué)',75);
insert into @tab(Class,Student,Course,Quantity) values('B班','王五','英語',85);
insert into @tab(Class,Student,Course,Quantity) values('B班','趙六','語文',35);
insert into @tab(Class,Student,Course,Quantity) values('B班','趙六','數(shù)學(xué)',45);
insert into @tab(Class,Student,Course,Quantity) values('B班','趙六','英語',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(語文) as 語文
,avg(數(shù)學(xué)) as 數(shù)學(xué)
,avg(英語) as 英語
,avg(總分) as 總分
from (
select Class,Student
,(select isnull(sum(Quantity),0) from @tab where Class=t.Class and Student=t.Student and Course='語文') as '語文'
,(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='英語') as '英語'
,(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,語文,數(shù)學(xué),英語,總分 with rollup
having Grouping(語文)=1
and Grouping(數(shù)學(xué))=1
and Grouping(英語)=1
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章