select "姓名", sum(case "课程" when '网络' then "分数" else 0 end) as "网络", ... sum("分数") as "总分" from group by "姓名"
select "姓名", sum(case "课程" when '网络' then "分数" else 0 end) as "网络", ... sum("分数") as "总分" from 成绩表group by "姓名"
这个SQL可以用一个游标拼出来,这样你就不用担心课程不固定了。 创建游标的结果集是: select distinct "分数" from 成绩表
表名 s_grade假设表的结构 ID VARCHAR2(10) --学号 NAME VARCHAR2(10) --姓名 SUBJECT VARCHAR2(10) --科目 GRADE NUMBER --成绩表类数据 NAME SUBJECT GRADE ID ---------- ---------- --------- ---------- qq1 数学 90 001 qq2 数学 91 002 qq3 数学 92 003 qq1 语文 80 001 qq2 语文 82 002 qq3 语文 89 003 qq2 外语 75 002 qq3 外语 70 003 qq1 外语 78 001sql 语句select a.id,a.name, nvl(语文,0) 语文, nvl(数学,0) 数学, nvl(外语,0) 外语, nvl(sum,0) sum from (select distinct id,name from s_grade) a, (select id,name, grade as 语文 from s_grade where subject='语文') b , (select id,name, grade as 数学 from s_grade where subject='数学') c , (select id,name, grade as 外语 from s_grade where subject='外语') d , (select id,name, sum(grade) sum from s_grade group by id,name) e where a.id = b.id(+) and a.id = c.id(+) and a.id = d.id(+) and a.id = e.id(+);结果 ID NAME 语文 数学 外语 SUM ---------- ---------- --------- --------- --------- --------- 001 qq1 80 90 78 248 002 qq2 82 91 75 248 003 qq3 89 92 70 251
columns:课程
Rows:学号 姓名
values:成绩
sum(case "课程" when '网络' then "分数" else 0 end) as "网络",
...
sum("分数") as "总分"
from
group by "姓名"
sum(case "课程" when '网络' then "分数" else 0 end) as "网络",
...
sum("分数") as "总分"
from 成绩表group by "姓名"
这个SQL可以用一个游标拼出来,这样你就不用担心课程不固定了。
创建游标的结果集是:
select distinct "分数"
from 成绩表
ID VARCHAR2(10) --学号
NAME VARCHAR2(10) --姓名
SUBJECT VARCHAR2(10) --科目
GRADE NUMBER --成绩表类数据
NAME SUBJECT GRADE ID
---------- ---------- --------- ----------
qq1 数学 90 001
qq2 数学 91 002
qq3 数学 92 003
qq1 语文 80 001
qq2 语文 82 002
qq3 语文 89 003
qq2 外语 75 002
qq3 外语 70 003
qq1 外语 78 001sql 语句select a.id,a.name,
nvl(语文,0) 语文,
nvl(数学,0) 数学,
nvl(外语,0) 外语,
nvl(sum,0) sum
from (select distinct id,name from s_grade) a,
(select id,name, grade as 语文 from s_grade where subject='语文') b ,
(select id,name, grade as 数学 from s_grade where subject='数学') c ,
(select id,name, grade as 外语 from s_grade where subject='外语') d ,
(select id,name, sum(grade) sum from s_grade group by id,name) e
where a.id = b.id(+)
and a.id = c.id(+)
and a.id = d.id(+)
and a.id = e.id(+);结果
ID NAME 语文 数学 外语 SUM
---------- ---------- --------- --------- --------- ---------
001 qq1 80 90 78 248
002 qq2 82 91 75 248
003 qq3 89 92 70 251