有如下表
--------------------------
Id 课程 成绩 学号
1 语文 89 1
2 英语 67 1
3 语文 77 2
4 英语 58 3
5 语文 66 4
6 英语 55 4
..............
交换同一个学生的英语和语文成绩,用sql写大家谁知道么
--------------------------
Id 课程 成绩 学号
1 语文 89 1
2 英语 67 1
3 语文 77 2
4 英语 58 3
5 语文 66 4
6 英语 55 4
..............
交换同一个学生的英语和语文成绩,用sql写大家谁知道么
--加条数据先,比如
insert into tb(课程,成绩,学号)
select 'test',0,1update a set 成绩=b.成绩 from tb a ,tb b where a.学号=b.学号 and a.课程='test' and b.课程='语文'
update a set 成绩=b.成绩 from tb a ,tb b where a.学号=b.学号 and a.课程='语文' and b.课程='英语'
update a set 成绩=b.成绩 from tb a ,tb b where a.学号=b.学号 and a.课程='英语' and b.课程='test'--是不是走弯路了- -
insert into tb values(1 ,'语文', 89 ,1)
insert into tb values(2 ,'英语', 67 ,1)
insert into tb values(3 ,'语文', 77 ,2)
insert into tb values(4 ,'英语', 58 ,3)
insert into tb values(5 ,'语文', 66 ,4)
insert into tb values(6 ,'英语', 55 ,4)
goupdate tb
set 成绩 = (case when 课程 = '英语' then isnull((select 成绩 from tb where 学号 = t.学号 and 课程 = '语文'),成绩)
when 课程 = '语文' then isnull((select 成绩 from tb where 学号 = t.学号 and 课程 = '英语'),成绩)
else 成绩
end
)
from tb tselect * from tb
/*
Id 课程 成绩 学号
----------- ---------- ----------- -----------
1 语文 67 1
2 英语 89 1
3 语文 77 2
4 英语 58 3
5 语文 55 4
6 英语 66 4(所影响的行数为 6 行)
*/drop table tb