当前位置: 代码迷 >> Sql Server >> 一个sql语句怎么写
  详细解决方案

一个sql语句怎么写

热度:80   发布时间:2016-04-24 18:32:27.0
求助一个sql语句如何写
当前有2个表
表A:
indexA indexB number
   1         11         123
   1         12         234
   1         13         345
   2         21         123
   2         22         234
   3         23         123
表B:
indexA indexB number
   1         12         230
   1         13         12
   2         21         50
   2         22         0

期待结果:
表C:
indexA indexB number
   1         11         123
   1         12         230
   1         13         12
   2         21         50
   2         22         0


匹配规则:
1.indexB唯一
2.基于表B中存在的indexA,取出表B所有的indexB
3.如果表B有对应的indexB,则number取表B的number,否则取表A的number

另外,表A比较大,表B比较小。
如何来写sql?并尽可能提高效率。
我尝试用case,结果总是不对。
大神来帮忙吧。。。
------解决方案--------------------
试试这个:
--drop table a,B

create table A(indexA  int, indexB int, number int)

insert into a
 select  1         ,11         ,123 union all
 select  1         ,12         ,234 union all
 select  1         ,13         ,345 union all
 select  2         ,21         ,123 union all
 select  2         ,22         ,234 union all
 select  3         ,23         ,123


create table B(indexA int,indexB int,number int)

insert into B
select   1         ,12         ,230 union all
select   1         ,13         ,12 union all
select   2         ,21         ,50 union all
select   2         ,22         ,0
go


select t.indexA ,t.indexB,ISNULL(b.number,a.number) number
from 
(
select distinct indexA from B
)tt
inner join
(
select indexA , indexB from a 
union 
select indexA , indexB from B
)t
 on tt.indexA = t.indexA
left join B
       on b.indexA = t.indexA and b.indexB = t.indexB
left join a
       on a.indexA = t.indexA and a.indexB = t.indexB
/*
indexA indexB number
1 11 123
1 12 230
1 13 12
2 21 50
2 22 0
*/    

------解决方案--------------------
select a.indexa,a.indexb,case when b.number is null then a.number else b.number end as number from
A left join B on a.indexb=b.indexB 
where exists(select * from B as c where a.indexa=c.indexa)
------解决方案--------------------
借用小当家的数据
 create table A(indexA  int, indexB int, number int)
 
insert into a
 select  1         ,11         ,123 union all
  相关解决方案