带条件字段的SQL联合

时间:2015-02-23 18:33:43

标签: sql-server union

我有以下(简化)表格:

No0    |    No1    |    start0    |    end0
10000  |           |              |
19999  |           |     10000    |    19999
20000  |           |              |
29999  |           |     20000    |    29999


No0    |    No1    |    start0    |    end0
       |   11000   |              |     
       |   15950   |              |    15950
       |   16000   |              |

我如何UNION他们(或其他方法),但根据No0 No1和{{1}之间的start0在第二张表格中填写相应的end0所以它返回:

No0    |    No1    |    start0    |    end0
10000  |           |              |
19999  |           |     10000    |    19999
20000  |           |              |
29999  |           |     20000    |    29999
19999  |   11000   |              |     
19999  |   15950   |              |    
19999  |   16000   |              |

1 个答案:

答案 0 :(得分:1)

在联合的下半部分,返回TableA,其中No1在Start0和End0之间。

以下是一个例子:

select      ta.No0,
            ta.No1,
            ta.Start0,
            ta.End0
from        TableA  as  ta
union all
select      ta.No0,
            tb.No1,
            NULL as Start0,
            NULL as End0
from        TableB  as  tb
inner join  TableA  as  ta  on  tb.No1 between ta.Start0 and ta.End0;

SQLFiddle