当前位置: 代码迷 >> Sql Server >> 如果用left outer join连接查询以下的两个表?该如何解决
  详细解决方案

如果用left outer join连接查询以下的两个表?该如何解决

热度:110   发布时间:2016-04-27 19:10:08.0
如果用left outer join连接查询以下的两个表?
表1:
名称 数量
R 1
R 2
R 4
R 6

表2:
名称 数量 金额
R 0 2
R 0 4
R 1 5
R 5 3
R 8 6

"说明:当表1数量为1时,可以连接表2中金额的2或4
  当表1数量为2时,可以连接表2中金额的5
  当表1数量为4时,可以连接表2中金额的5
  当表1数量为6时,可以连接表2中金额的3
规律:根据左表进行连接,且只能连接与表2数量低且最接近数量的金额

合成后的结果表:
数量(表1) 金额(表2)
1 2
1 4
2 5
4 5
6 3




------解决方案--------------------
要根据算法写,不能根据数据来写

SQL code
---测试数据---if object_id('[表1]') is not null drop table [表1]gocreate table [表1]([名称] varchar(1),[数量] int)insert [表1]select 'R',1 union allselect 'R',2 union allselect 'R',4 union allselect 'R',6if object_id('[表2]') is not null drop table [表2]gocreate table [表2]([名称] varchar(1),[数量] int,[金额] int)insert [表2]select 'R',0,2 union allselect 'R',0,4 union allselect 'R',1,5 union allselect 'R',5,3 union allselect 'R',8,6 ---查询---select   a.数量1 as 数量,  b.金额from(select   数量 as 数量1,  (select max(数量) from [表2] where 数量<t.数量) as 数量2from [表1] t) aleft join [表2] bon a.数量2=b.数量---结果---数量          金额          ----------- ----------- 1           21           42           54           56           3(所影响的行数为 5 行)
------解决方案--------------------
不好意思上面有个地方写反了




if object_id('a') is not null
drop table a
go
create table a([名称] varchar(10),[数量] int)
delete from a
insert a select 'R',1
insert a select 'R',2
insert a select 'R',4
insert a select 'R',6
insert a select 'R',-1
go
if object_id('b') is not null
drop table b
go
create table b([名称] varchar(10),[数量] int,[金额] int)
insert b select 'R','0','2'
insert b select 'R','0','4'
insert b select 'R','1','5'
insert b select 'R','5','3'
insert b select 'R','8','6'
go



select a.[名称],a.数量,b.[金额]
from 
(
select [名称],数量1,max(数量2) as 数量2
from
(
select a.数量 as 数量1,b.数量 as 数量2,a.[名称]
from a
left join b
on a.数量>b.数量 and a.[名称]=b.[名称]
) c
group by [名称],数量1
) d
left join a on d.[名称]=a.[名称] and d.数量1=a.数量 
left join b on d.[名称]=b.[名称] and d.数量2=b.数量 

------解决方案--------------------
select 
[表1].数量
,[表2].金额
from
[表1] left join 
(select 
,(select min([表1].数量) from [表1] where [表1].数量>[表2].数量) as 数量
,[表2].金额
from [表2]
) as [表2]
on [表1].数量=[表2].数量
  相关解决方案