日期:2014-05-18  浏览次数:20812 次

有点难度的sql问题,请高手帮忙
表A
字段落
id               name             sex    
201             张三             男
202             李四             男
203             光头             男
204             初恋             女
205             失恋             女


表B
id             score
201           98
202           87
205           67


现在问题是我要查询所有的字段,但是要把没有成绩的学生以0分计算

问题解决立即结贴

------解决方案--------------------
select a.name,[score]=isnull(b.score,0)
from a left join b on a.id=b.id
------解决方案--------------------
--2000或以下版本可以用这样的方式
select a.name,[score]=isnull(b.score,0)
from a ,b
where a.id*=b.id

------解决方案--------------------
SELECT a.name,isnull(b.score,0) [score]
FROM a LEFT JOIN b ON a.id=b.id
ORDER BY a.id
------解决方案--------------------
create table tb_a(id varchar(10),name varchar(10), sex varchar(10))
insert tb_a select '201 ', '张三 ', '男 '
union all select '202 ', '李四 ', '男 '
union all select '203 ', '光头 ', '男 '
union all select '204 ', '初恋 ', '女 '
union all select '205 ', '失恋 ', '女 '

create table tb_b(id varchar(10),score int)
insert tb_b select '201 ',98
union all select '202 ',87
union all select '205 ',67
union all select '206 ',99

--方法一
select
[id]=isnull(a.id,b.id),
a.name,
[score]=isnull(b.score,0)
from tb_a a
full join tb_b b on a.id=b.id
order by a.id

drop table tb_a,tb_b

/*
id name score
------------------------
201 张三 98
202 李四 87
203 光头 0
204 初恋 0
205 失恋 67
206 NULL 99
*/
------解决方案--------------------
select a.name,CASE when score is null then 0 else score end as score1
from
tb_a a
left join
tb_b b
on a.id=b.id
------解决方案--------------------
select a.name,[score]=isnull(b.score,0) from a left join b on a.id=b.id
---------------------------------
正解!

我就问过这样的问题,只不过看着比你的复杂而已!
------解决方案--------------------
--a.id*=b.id 是什么意思啊?
就是一个左连符号

select a.name,[score]=(case b.score when null then 0 else b.score end)
from a left join b on a.id=b.id


------解决方案--------------------
select a.id,a.name,isnull(c.score,0) as score from
A.a left join B.b on a.id=b.id