在数据透视查找表中查找值

Find Value in Pivoted LookupTable

我正在尝试找出从旋转查找中查询的最佳方法 table。

理想情况下,您可以查找 table 3 列

min, max, value
 1,   2,   a
 2,   3,   b
 3,   4,   c

在这里你可以编写代码来拉取正确的输出:

select value from table
where input >= min and input < max

因此,如果输入 = 1.5,则值 = a,如果输入 = 2.5,则值 = b。由于行不相交,

但是,我们的 table 必须按以下方式构建,因为这是一个非常糟糕的一次性情况。

1,2,3,4
a,b,c,-

我将如何创建查询来查找此类 table 中的值?

感谢观看!

我相信您正在寻找 CASE WHEN 语句

Select case when min >= 1 and max <3 then 'A'
            when min >= 2 and max <4 then 'B'
            when min >= 3 and max <5 then 'C'

       else NULL
       end Value

 From table

希望对您有所帮助

However, our table has to be constructed in the following manner as this is a janky one off situation.

您有两个选择:



逆透视这个 table 然后从这个子查询的结果中查询
以同样的方式 SELECT value FROM ( subquery ) ...:

SELECT 1 as min, 2 as max, "1" as value FROM table1
UNION ALL
SELECT 2 as min, 3 as max, "2" asvalue FROM table1
Union All
SELECT 3 as min, 4 as max, "3" asvalue FROM table1

演示:http://sqlfiddle.com/#!17/b6b4d/2

| min | max | value |
|-----|-----|-------|
|   1 |   2 |     a |
|   2 |   3 |     b |
|   3 |   4 |     c |

您可以使用上述查询和针对此视图的 运行 查询创建视图。


假设此 table 中只有 1 行 - 构建这样的查询:

SELECT CASE
       WHEN input >=1 AND input < 2 THEN "1"
       WHEN input >=2 AND input < 3 THEN "2"
       WHEN input >=3 AND input < 4 THEN "3"
       END As value
FROM Table1