当前位置:Gxlcms > mssql > 一句Sql把纵向表转为横向表,并分别分组求平均和总平均值

一句Sql把纵向表转为横向表,并分别分组求平均和总平均值

时间:2021-07-01 10:21:17 帮助过:85人阅读

效果如图所示:

测试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

您可能感兴趣的文章:

  • sql分组后二次汇总(处理表重复记录查询和删除)的实现方法
  • SQL SERVER 分组求和sql语句
  • 显示同一分组中的其他元素的sql语句
  • sql获取分组排序后数据的脚本
  • SQL进行排序、分组、统计的10个新技巧分享
  • SQL分组排序去重复的小实例
  • 以数据库字段分组显示数据的sql语句(详细介绍)
  • SQL中Group分组获取Top N方法实现可首选row_number
  • Sql Server:多行合并成一行,并做分组统计的两个方法
  • Sql Server 分组统计并合计总数及WITH ROLLUP应用
  • SQL语句分组获取记录的第一条数据的方法
  • sqlserver巧用row_number和partition by分组取top数据
  • sql 分组查询问题
  • SQLserver 实现分组统计查询(按月、小时分组)
  • 分组后分组合计以及总计SQL语句(稍微整理了一下)

人气教程排行