SQL行列轉化案例(成績表+學籍表)

原表:
在這裏插入圖片描述
1.創表和插入數據:

-- 建表語句
create table 成績表 (
學號 varchar(12),
科目 varchar(11),
成績 int
);

insert into 成績表  values('001','語文','80');
insert into 成績表  values('002','語文','66');
insert into 成績表 values('001','數學','60');
insert into 成績表  values('002','數學','72');

create table 學籍表 (
學號 varchar(12),
姓名 varchar(12),
班級 varchar(12)
);

insert into  學籍表 values('001','張三','01');
insert into  學籍表 values('002','李四','02');

2.代碼實現:

-- 方法1: 
SELECT
c.*,(語文+數學) AS 總分
FROM
(
SELECT a.學號,a.姓名,b.語文,b.數學
FROM 學籍表 a 
INNER JOIN
(select 學號,
max(case 科目 when'語文' then 成績 else 0 end ) as '語文',
max(case 科目 when'數學' then 成績 else 0 end) as'數學',
SUM(成績) 總分
from 成績表 group by 學號 )b  
ON a.學號 = b.學號) c

-- 方法2:

SELECT a.學號,姓名,語文,數學,總分 FROM 學籍表 b
left join 
(select
成績表.學號,
max(case when 科目='語文' then 成績 end) as 語文,
max(case when 科目='數學' then 成績 end) as 數學,
sum(成績) as 總分
from 成績表
group by 成績表.學號) a
on a.學號 = b.學號

-- ERROR AISHUJUXUEYUAN爲錯解
select
學籍表.學號,
姓名,
max(case when 科目='語文' then 成績 end) as 語文,
max(case when 科目='數學' then 成績 end) as 數學,
sum(成績) as 總分
from 成績表
left join 學籍表
on 成績表.學號 = 學籍表.學號
group by 成績表.學號;
/*
1055 - Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.csv.學籍表.姓名' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章