sql server 学习小记1

来源:互联网 发布:魔兽争霸mac版cd key 编辑:程序博客网 时间:2024/06/04 22:47

--====================
--author:yeeXun
--date:2010-11-21
--address:17-304
--====================

use practiceDB
go
create table 成绩表 (姓名 varchar(4),科目 varchar(4),分数 int);
insert into 成绩表
select '张三','数学',90 union all
select '李四','数学',80 union all
select '王五','数学',70 union all
select '张三','语文',60 union all
select '李四','语文',50 union all
select '王五','语文',40 union all
select '赵六','数学',30 union all
select '赵六','语文',20
go

create table 补考成绩表(姓名 varchar(4),科目 varchar(4),分数 int);
insert into 补考成绩表
select '李四','语文',70 union all
select '王五','语文',75
go
/*
require:
1、想把成绩表中不及格的,并参加补考及格的,更新成“补及”。
2、想把成绩表中不及格的,并参加补考及格的,更新成补考成绩。
*/

alter table 成绩表 alter column 分数 varchar(10)
select * from 补考成绩表
select * from 成绩表
go
update 成绩表
set 分数='补及'
from 成绩表 a,补考成绩表 b
where a.姓名=b.姓名 and a.科目=b.科目 and cast(b.分数 as int)>60;

go
select * from 成绩表
go
drop table 成绩表
drop table 补考成绩表


别人的解法
declare @成绩表 table (姓名 varchar(4),科目 varchar(4),分数 int)
insert into @成绩表
select '张三','数学',90 union all
select '李四','数学',80 union all
select '王五','数学',70 union all
select '张三','语文',60 union all
select '李四','语文',50 union all
select '王五','语文',40 union all
select '赵六','数学',30 union all
select '赵六','语文',20

declare @补考成绩表 table (姓名 varchar(4),科目 varchar(4),分数 int)
insert into @补考成绩表
select '李四','语文',70 union all
select '王五','语文',75

select a.*,b.科目 as 补及,b.分数 as 新分数 from @成绩表 a
left join @补考成绩表 b
on a.姓名=b.姓名
and a.科目=b.科目


========================================================
create table #tbA(fcode char(7),incode char(3),qname char(3))
create table #tbB(fcode char(7),name char(4))
go
insert into [#tbA]
select 'f123456','000','000' union all
select 'f234567','111','222'
go
insert into [#tbB]
select 'f123456','张三' union all
select 'f234567','李四'
go
/*
require:
当 incode=qname 输出 fcode qname
当 incode<>qname 输出 fcode name
*/
solution 1:
select a.fcode,a.qname as mingzi
from [#tbA] a, [#tbB] b where a.fcode=b.fcode and a.incode=a.qname
union all
select a.fcode,b.name as mingzi
from [#tbA] a, [#tbB] b where a.fcode=b.fcode and a.incode<>a.qname
go
solution 2:
select a.fcode,
case when a.incode=a.qname then a.qname else b.name end as mingzi
from [#tbA] a inner join [#tbB] b on a.fcode=b.fcode

drop table [#tbB]