比较两个结果集以查找值是否介于最小值和最大值之间

时间:2013-07-24 18:54:45

标签: sql-server tsql

我有一个复杂的查询,它给了我这个结果

Area  MinValue  MaxValue
A      12.34     34.45
B      34.23     41.23
C      10.23     15.12

现在,从另一张桌子上我正在计算每个区域

Area  Count
A     24
B     50
C     15
D     22

我必须比较这两个结果集,以找出哪个区域数不在minvalue和maxvalue之间。

预期结果集:

Area MinValue MaxValue CurrentValue 
B    34.23     41.23      50

3 个答案:

答案 0 :(得分:3)

您必须先在Area上加入两个结果集,然后过滤结果。

SELECT a.[Area], a.[MinValue], a.[MaxValue], b.[Count] AS CurrentValue
FROM [complexQueryTable] a
JOIN [anotherTable] b
    ON b.[Area] = a.[Area]
WHERE b.[Count] NOT BETWEEN a.[MinValue] AND a.[MaxValue]

SQL Demo

| AREA | MINVALUE | MAXVALUE | CURRENTVALUE |
---------------------------------------------
|    B |       34 |       41 |           50 |

答案 1 :(得分:2)

SELECT
     QueryB.Area,
     QueryA.MinValue,
     QueryA.MaxValue,
     QueryB.Count AS CurrentValue
FROM ( /* Your first query */ ) QueryA
JOIN ( /* Your second query */) QueryB ON QueryA.Area = QueryB.Area
WHERE QueryB.Count NOT BETWEEN QueryA.MinValue AND QueryB.MaxValue

答案 2 :(得分:1)

尝试

    SELECT T1.Area, MinValue, MaxValue, Count AS CurrentValue
    FROM Table1 T1 
    INNER JOIN Table2 T2 
    ON T1.Area=T2.Area
    WHERE Count < MinValue AND Count > MaxValue