Oracle把成績行的方式轉成列
來源:程序員人生 發布時間:2015-04-21 09:19:23 閱讀次數:3833次
1、表格中有以下數據
姓名 |
科目 |
1月 |
2月 |
3月 |
張3 |
語文 |
30 |
40 |
50 |
張3 |
數學 |
56 |
65 |
78 |
張3 |
英語 |
28 |
86 |
48 |
李4 |
語文 |
31 |
41 |
51 |
李4 |
數學 |
57 |
66 |
79 |
李4 |
英語 |
29 |
87 |
49 |
先要轉換成
姓名 |
1月語文 |
2月語文 |
3月語文 |
1月數學 |
2月數學 |
3月數學 |
1月英語 |
2月英語 |
3月英語 |
李4 |
31 |
41 |
51 |
57 |
66 |
79 |
29 |
87 |
49 |
張3 |
30 |
40 |
50 |
56 |
65 |
78 |
28 |
86 |
48 |
2、建測試數據
CREATE TABLE GRADE_TABLE(
STU_NAME VARCHAR(20),
SUBJECT VARCHAR(20),
MONTH1 INT DEFAULT 0, --1月
MONTH2 INT DEFAULT 0,--2月
MONTH3 INT DEFAULT 0
);
insert into GRADE_TABLE(STU_NAME,SUBJECT,MONTH1,MONTH2,MONTH3) values('張3','語文','30','40','50');
insert into GRADE_TABLE(STU_NAME,SUBJECT,MONTH1,MONTH2,MONTH3) values('張3','數學','56','65','78');
insert into GRADE_TABLE(STU_NAME,SUBJECT,MONTH1,MONTH2,MONTH3) values('張3','英語','28','86','48');
insert into GRADE_TABLE(STU_NAME,SUBJECT,MONTH1,MONTH2,MONTH3) values('李4','語文','31','41','51');
insert into GRADE_TABLE(STU_NAME,SUBJECT,MONTH1,MONTH2,MONTH3) values('李4','數學','57','66','79');
insert into GRADE_TABLE(STU_NAME,SUBJECT,MONTH1,MONTH2,MONTH3) values('李4','英語','29','87','49');
3、處理SQL
select stu_name,sum(1月語文 ) 1月語文 ,sum(2月語文 ) 2月語文,sum(3月語文 ) 3月語文
,sum(1月數學 ) 1月數學 ,sum(2月數學 ) 2月數學,sum(3月數學 ) 3月數學
,sum(1月英語 ) 1月英語 ,sum(2月英語 ) 2月英語,sum(3月英語 ) 3月英語
from(
select stu_name,sum(case subject when '語文' then month1 end) as 1月語文
,sum(case subject when '語文' then month2 end) as 2月語文
,sum(case subject when '語文' then month3 end) as 3月語文
,sum(case subject when '數學' then month1 end) as 1月數學
,sum(case subject when '數學' then month2 end) as 2月數學
,sum(case subject when '數學' then month3 end) as 3月數學
,sum(case subject when '英語' then month1 end) as 1月英語
,sum(case subject when '英語' then month2 end) as 2月英語
,sum(case subject when '英語' then month3 end) as 3月英語
from GRADE_TABLE
group by stu_name,subject
) group by stu_name --danielinbiti
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈