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

所属分类: 数据库 / MsSql 阅读数: 1722
收藏 0 赞 0 分享
效果如图所示:

测试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 SERVER 删除重复内容行

刚解决的小问题,之前也解决过类似的问题,但这次还设计到用SQL语句加一列,平时不常用这种命令,还是记录一下吧。
收藏 0 赞 0 分享

SQL SERVER 的SQL语句优化方式小结

千辛万苦,终于把数据库服务器的CPU从超过50%(开5个程序线程)乃至100%(开10个程序线程)降低到了5%。摸索到了一些门道,总结一下
收藏 0 赞 0 分享

数据库高并发情况下重复值写入的避免 字段组合约束

10线程同时操作,频繁出现插入同样数据的问题的解决方法。大家可以参考下。
收藏 0 赞 0 分享

一个有趣的SQL命题 用一条语句切换BIT型的真假值

有个需求,用一条SQL语句(SQL SERVER)的,切换某个BIT字段值。也就是说从TRUE变FALSE,从FALSE到TRUE。
收藏 0 赞 0 分享

AspNetPager分页控件 存储过程

我用AspNetPager分页控件,写的存储过程
收藏 0 赞 0 分享

SQL Server自动生成日期加数字的序列号

需要生成下面的序列号,前半部分是yyyymmdd格式的年月日时间数字,后半部分则是每天都从1顺序增长的数字,位数要固定,中间不足的补0。
收藏 0 赞 0 分享

远程连接局域网内的SQL Server 的方法

下面我们依次介绍如何来解决这三个最常见的连接错误。
收藏 0 赞 0 分享

把数据批量插入具有Identity列的表的方法

把数据批量插入具有Identity列的表的方法。
收藏 0 赞 0 分享

SQL Server 索引维护sql语句

SQL Server 索引维护sql语句,有需要的朋友可以参考下。
收藏 0 赞 0 分享

从两种SQL表连接写法来了解过去

如果想要优雅而易于维护且不容易写错的代码,当然用高标准的第二种方法。 如果必要考虑风险这个因素,比如涉及到多种平台的迁移或者整合,你应该用第一种,起码在两个表的情况下他还是比较安全的。
收藏 0 赞 0 分享
查看更多