SQL 2012语句返回范围中的查找值

时间:2015-03-18 13:02:41

标签: sql-server common-table-expression

所以我有2张桌子,

Table A has 3 columns: 
    NumberRangeStart, NumberRangeEnd, RangeName
Table B has 2 columns: 
    Number, RangeName

我想输出

TableC:
    B.Number, B.RangeName, A.NumberRange, A.RangeName

我想查找B.Number位于A.NumberRangeStart and A.NumberRangeEnd之间的位置,并报告已分配的RangeName

任何想法如何在SQL 2012中实现这一目标? 我想我需要一个CTE,但不确定如何去做!

3 个答案:

答案 0 :(得分:1)

这类似于在insert语句中使用的简单的两个条件内连接。

INSERT INTO TableC
SELECT
    TableB.Number,
    TableB.RangeName,
    TableA.NumberRangeStart,
    TableA.NumberRangeEnd,
    TableA.RangeName
FROM TableA
INNER JOIN TableB ON TableB.Number BETWEEN TableA.NumberRangeStart AND TableA.NumberRangeEnd
-- Optional based on clarification
WHERE TableA.RangeName <> TableB.RangeName;

答案 1 :(得分:1)

create table #TableA (
    NumberRangeStart int,
    NumberRangeEnd int,
    RangeName nvarchar(200))

create table #TableB (
    Number int)

insert into #TableA values (0, 100, '0 to 100'), (50, 70, '50 to 70'), (150, 1000, '150 to 1000')

insert into #TableB values (10), (20), (40), (60), (200), (2000)

select  b.Number, coalesce(a.Rangename, 'Not in any range')
from    #TableB b left join #TableA a on b.Number between a.NumberRangeStart and a.NumberRangeEnd

答案 2 :(得分:0)

也许:

SELECT DISTINCT B.RangeName
FROM TableB B
WHERE EXISTS
(
    SELECT 1 FROM TableA A
    WHERE A.RangeName = B.RangeName
    AND   B.Number BETWEEN A.NumberRangeStart AND A.NumberRangeEnd
)