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

还是没有人能解决啊,高手路过不要错过啊!!!
表1 
A,B,C,D 
aa,1,100,100 
aa,501,800,300 
aa,401,450,50 
cc,11,500,490
...... 
表2 
A,B,C,D 
aa,1,1000,1000 
cc,1,6000,6000
..... 
怎么样从表1中找出在表2中没有数据范围。 
B:开始的数字 
C:结束的数字 
我要得到的结果是: 
A,B,C,D 
aa,101,401,400 
aa,451,500,50 
aa,801,1000,200 
cc,1,10,10
cc,501,6000,5500
怎么在SQL中实现啊!

------解决方案--------------------
B表中区域不重叠:
create table #表1(A varchar(10),B int,C int,D int )
insert #表1 select
'aa ',1,100,100 insert #表1 select
'aa ',501,800,300 insert #表1 select
'aa ',401,450,50 insert #表1 select
'cc ',11,500,490 insert #表1 select
'aa ',801,950,150 insert #表1 select
'cc ',6000,6000,1 insert #表1 select
'cc ',1,1,1
create table #表2 (A varchar(10),B int,C int,D int )
insert #表2 select
'aa ',1,1000,1000 insert #表2 select
'cc ',1,6000,6000 insert #表2 select
'aa ',1001,2000,1000 insert #表2 select
'cc ',6001,7000,1000 insert #表2 select
'cc ',7002,8000,999 

declare @ta table(A varchar(10),B int,C int,id int identity(1,1)) 
insert @ta select A,B,C+1 C from #表1 union select A,C+1,C+1 from #表2 union select A,B,B from #表2 
order by A,B,C
---select * from @ta 
select A,BB B,CC C,CC-BB+1 D from
(
select A,C BB,id,CC=(select top 1 B-1 from @ta tb where ta.A=tb.A and ta.id <tb.id order by tb.id)
from @ta ta
)a where CC is not null and CC-BB+1<>0 order by id
---------------------
aa 101 400 300
aa 451 500 50
aa 951 1000 50
aa 1001 2000 1000
cc 2 10 9
cc 501 5999 5499
cc 6001 7000 1000
cc 7001 7001 1
cc 7002 8000 999