本帖最后由 zhbdabing 于 2010-02-23 15:43:09 编辑

解决方案 »

  1.   

    结果错了,好多重复了,应该是查询得到目的表格式 
    s,t,dept1,dept2 
    1,1,1,2 
    2,NULL,3,3 
    2,2,4,5 
    NULL,2,6,6 
    3,NULL,7,9 
    NULL,3,12,19 
      

  2.   

    --表【1】 
    declare @t1 table(
    s int,
    dept1 int,
    dept2 int
    )
    insert @t1 select 
    1,1,2 union all select
    2,3,5  union all select
    3,7,9 --表【2】 
    declare @t2 table(
    t int,
    dept1 int,
    dept2 int
    )
    insert @t2 select 
    1,1,2 union all select
    2,4,9 union all select
    3,12,19 declare @depts table (
     dept int
     )
     
    insert @depts
    select dept1 from @t1
    union select dept2 from @t1
    union select dept1 from @t2
    union select dept2 from @t2select 
    c.s,d.t,a.dept as dept1,b.dept as dept2 
    from @depts a inner join @depts b
    on a.dept <b.dept and not exists (select 1 from @depts where dept>a.dept and dept<b.dept )
    left join @t1 c
    on c.dept1 <= a.dept and c.dept2 >= b.dept 
    left join @t2 d
    on d.dept1 <= a.dept and d.dept2 >= b.dept 
    where not (c.s is null and d.t is null)
    --查询得到目的表格式 
    s t dept1 dept2
    1 1 1 2
    2 NULL 3 4
    2 2 4 5
    NULL 2 5 7
    3 2 7 9
    NULL 3 12 19