国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > SQL Server > 正文

一句Sql把縱向表轉為橫向表,并分別分組求平均和總平均值

2024-08-31 00:58:39
字體:
來源:轉載
供稿:網友
效果如圖所示:

一句Sql把縱向表轉為橫向表,并分別分組求平均和總平均值


測試sql語句如下:

復制代碼 代碼如下:


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班','張三','數學',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班','李四','數學',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班','王五','數學',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班','趙六','數學',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(數學) as 數學
,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='數學') as '數學'
,(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,語文,數學,英語,總分 with rollup
having Grouping(語文)=1
and Grouping(數學)=1
and Grouping(英語)=1

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黄大仙区| 西乌珠穆沁旗| 安乡县| 德钦县| 左云县| 延安市| 金门县| 兴安盟| 榆社县| 洛隆县| 九寨沟县| 闵行区| 紫云| 扎兰屯市| 萝北县| 永嘉县| 喀喇沁旗| 汪清县| 和龙市| 夏河县| 湘乡市| 河北区| 定日县| 宣恩县| 昭觉县| 南宁市| 林芝县| 乌兰察布市| 鄂伦春自治旗| 马尔康县| 仪陇县| 成安县| 安徽省| 个旧市| 池州市| 三亚市| 平遥县| 福清市| 古浪县| 永顺县| 张北县|