日期:2014-05-19  浏览次数:20546 次

学生成绩按次数分组求合

原数据表结构如下
回数 语文 数学 英语 政治
1 60 76 73 62
2 67 90 78 76
3 99 80 81 32
4 94 50 67 72
5 80 35 97 82
6 83 83 74 92
7 82 89 76 32
....
....
....
最多是八回


变选出记录的结果是
第一回 第二回 第三回 第四回.....最多是八回 平均值
语文 60 67 99 94 80........ (1-8回语文的平均值
数学 ......
英语 ......
政治 ......

帮帮我!

谢谢了,
虽说是用程序组合出来了,
但还是希望写成SQL文出来!!

------解决方案--------------------
还是行转列问题,查查,代码多了
------解决方案--------------------
最多8回? 如果是定死的話,也可以不用動態語句,寫死就OK
------解决方案--------------------
不是一般的行转列

他这个应该叫列转行
写起来很别扭
------解决方案--------------------
1、既然最多只有8回的话,你就固定好了,列用case when 语句进行组合。
2、列的话,用多个union all 进行组合,就是说第一次我只查询语文的,union all 查询数学的,

这样可以达到你的效果吧

------解决方案--------------------
select ex1, sum(回1) as 回1,sum(回2)as 回2
from(
select '语文 ' as ex1, case when 回数=1 then 语文 else 0 end as 回1,
, case when 回数=2 then 语文 else 0 end as 回2
from table1
union all
select '数学 ' as ex1, case when 回数=1 then 数学 else 0 end as 回1,
, case when 回数=2 then 数学 else 0 end as 回2
from table1
)
group by ex1
------解决方案--------------------
--建表
create table test
(
回数 int,
语文 int,
数学 int,
英语 int,
政治 int
)

insert into test select 1,60,76,73,62
insert into test select 2,67,90,78,76
insert into test select 3,99,80,81,32
insert into test select 4,94,50,67,72
insert into test select 5,80,35,97,82
insert into test select 6,83,83,74,92
insert into test select 7,82,89,76,32

--语句
select '语文 ' as [科目],sum(case 回数 when 1 then 语文 end) as 第一回,
sum(case 回数 when 2 then 语文 end) as 第二回,
sum(case 回数 when 3 then 语文 end) as 第三回,
sum(case 回数 when 4 then 语文 end) as 第四回,
sum(case 回数 when 5 then 语文 end) as 第五回,
sum(case 回数 when 6 then 语文 end) as 第六回,
sum(case 回数 when 7 then 语文 end) as 第七回,
sum(case 回数 when 8 then 语文 end) as 第八回,
sum(语文)/count(1) as 平均数
from test
union all
select '数学 ' as [科目],sum(case 回数 when 1 then 数学 end) as 第一回,
sum(case 回数 when 2 then 数学 end) as 第二回,
sum(case 回数 when 3 then 数学 end) as 第三回,
sum(case 回数 when 4 then 数学 end) as 第四回,
sum(case 回数 when 5 then 数学 end) as 第五回,
sum(case 回数 when 6 then 数学 end) as 第六回,
sum(case 回数 when 7 then 数学 end) as 第七回,
sum(case 回数 when 8 then 数学 end) as 第八回,
sum(数学)/count(1) as 平均数
from test
union all
select '英语 ' as [科目],sum(case 回数 when 1 then 英语 end) as 第一回,
sum(case 回数 when 2 then 英语 end) as 第二回,
sum(case 回数 when 3 then 英语 end) as 第三回,
sum(case 回数 when 4 then 英语 end) as 第四回,
sum(case 回数 when 5 then 英语 end) as 第五回,
sum(case 回数 when 6 then 英语 end) as 第六回,
sum(case 回数 when 7 then 英语 end) as 第七回,