1

我在 ORACLE 中有一张这样的表

a     b
--   --
1000   1
100    2
10     3
1      4

例如,我的另一张表在名为 numbers 的列中有“67”或“112”之类的数字。如何使用这些值加入该表并获得正确的结果,其中 >=1000 为 1,>=100 为 2 >=10 为 3,以此类推。

我试着做一个

select g.b
from table o
join table2 g on o.column >= g.a

当我这样做时说 1002 是 g 的值,我会得到这些结果。1 2 3 4

当我只想 1

4

2 回答 2

2

最简单的情况是,如果您的查找表有范围而不是只有一个数字,例如第 1 行 = 1000,9999,1 和第 2 行 = 100,999,2 等。那么您的联接可能是

SELECT OtherTable.n, lookup.b
from OtherTable
LEFT JOIN lookup on OtherTable.n between lookup.low and lookup.high

但是,如果您真的想使用原始表,那么在 SQL Server 上,请执行以下操作:

/*CREATE TABLE #A (a int,b int)
INSERT INTO #A VALUES (1000,1),(100,2),(10,3),(1,4)

CREATE TABLE #B (n INT)
INSERT INTO #B VALUES (67),(112),(4),(2001)
*/
SELECT B.n,  A1.b
FROM #B B OUTER APPLY (SELECT TOP 1 a,b FROM #A A WHERE A.a<B.n ORDER BY A.a DESC) A1
于 2013-03-29T02:12:59.387 回答
1

这是一种使用子查询来获取MAX列 a,然后在同一个表上重新加入以获取 b 的方法:

select t.numericvalue, t2.b
from (
  select t.numericvalue, max(t2.a) maxb
  from table1 t
    join table2 t2 on t.numericvalue >= t2.a
  group by numericvalue
  ) t join table2 t2 on t.maxb = t2.a

SQL 小提琴演示

于 2013-03-29T02:19:42.480 回答