Look up a list of values in the ranges (bins) as defined by two columns in another table and get the corresponding value from the third column

本秂侑毒 提交于 2020-01-24 19:52:11

问题


Hello I have two tables T1 and T2. T1 has a column of integer values. And T2 has ranges defined by two columns and a corresponding value for each range... Something like this:

range_min range_max  corr_value
   5         10         1020
   11        15         5000

Suppose I want to be able to get the "value" from T2 for each integer of T1 depending on which range the integer value falls into. Say, I have 6, 7, and 12 in T1. Then, the ideal result would look like this:

integer_val  corr_value
     6          1020
     7          1020
     12         5000

Note that I don't have anything to join on. I couldn't figure out how to do this using SQL. I don't know if it'll make a difference, but I am using HiveQL.

I really appreciate your help. Thank you!

Cheers


回答1:


You can use a non-equijoin. If your SQL supports between, use

select t1.integer_val, t2.corr_value
from t1
left outer join t2 on t1.integer_val between t2.range_min and t2.range_max

Otherwise, use

select t1.integer_val, t2.corr_value
from t1
left outer join t2 on t1.integer_val >= t2.range_min and t1.integer_val <= t2.range_max

Here is a reference to a mysql demo on sqlfiddle.

This query works as you describe only when there are no overlaps in the t1.




回答2:


select integer_val, corr_value
from t1 join t2 on integer_val >= range_min
and integer_val >= range_max


来源:https://stackoverflow.com/questions/14617711/look-up-a-list-of-values-in-the-ranges-bins-as-defined-by-two-columns-in-anoth

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!