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

如果用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]
go
create table [表1]([名称] varchar(1),[数量] int)
insert [表1]
select 'R',1 union all
select 'R',2 union all
select 'R',4 union all
select 'R',6
if object_id('[表2]') is not null drop table [表2]
go
create table [表2]([名称] varchar(1),[数量] int,[金额] int)
insert [表2]
select 'R',0,2 union all
select 'R',0,4 union all
select 'R',1,5 union all
select 'R',5,3 union all
select 'R',8,6
 
---查询---
select 
  a.数量1 as 数量,
  b.金额
from
(
select 
  数量 as 数量1,
  (select max(数量) from [表2] where 数量<t.数量) as 数量2
from [表1] t
) a
left join [表2] b
on a.数量2=b.数量


---结果---
数量          金额          
----------- ----------- 
1           2
1           4
2           5
4           5
6           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].数量