微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

效果如图所示:

测试sql语句如下:
<div class="codetitle"><a style="CURSOR: pointer" data="52402" class="copybut" id="copybut52402" onclick="doCopy('code52402')"> 代码如下:

<div class="codebody" id="code52402">
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,'数学',70);
insert into @tab(Class,'英语',80);
insert into @tab(Class,'李四',30);
insert into @tab(Class,40);
insert into @tab(Class,50); insert into @tab(Class,Quantity) values('B班','王五',65);
insert into @tab(Class,75);
insert into @tab(Class,85);
insert into @tab(Class,'赵六',35);
insert into @tab(Class,45);
insert into @tab(Class,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 '语文'
,0) from @tab where Class=t.Class and Student=t.Student and Course='数学') as '数学'
,0) from @tab where Class=t.Class and Student=t.Student and Course='英语') as '英语'
,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,语文,数学,英语,总分 with rollup
having Grouping(语文)=1
and Grouping(数学)=1
and Grouping(英语)=1

原文地址:https://www.jb51.cc/mssql/64106.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐