简体   繁体   English

查询以基于其他列获取最接近的匹配值

[英]Query to get closest match value based on other columns

Based on Table 1 below, I am trying to write a query that allows me to create a new table, fill up the empty companyID with closest match based on City, Country and Region. 基于下面的表1,我试图编写一个查询,使我可以创建一个新表,并根据城市,国家和地区填写最匹配的空公司ID。

Table 1 is the sample table, whereas Table 2 is the expected output. 表1是样本表,而表2是预期输出。

Table 1 表格1

Cust | City | Country | Region | CompanyID
ABC  |   KL |      MY |   APAC | 123456
ABC  |   KL |      MY |   APAC | 
ABC  |   JB |      MY |   APAC | 
ABC  |   SY |      AU |   APAC | 778899
ABC  |   ME |      AU |   APAC | 
GHI  |   DB |      AE |   EMEA | 112233
GHI  |   AD |      AE |   EMEA |

Table 2 表2

Cust | City | Country | Region | CompanyID
ABC  |   KL |      MY |   APAC | 123456
ABC  |   KL |      MY |   APAC | 123456
ABC  |   JB |      MY |   APAC | 123456
ABC  |   SY |      AU |   APAC | 778899
ABC  |   ME |      AU |   APAC | 778899
GHI  |   DB |      AE |   EMEA | 112233
GHI  |   AD |      AE |   EMEA | 112233

Feels a bit like a VLOOKUP thing but not sure how to start. 感觉有点像VLOOKUP,但不确定如何启动。 Will sincerely appreciate any help please. 请真诚的感谢您的帮助。

Thanks! 谢谢!

In a subquery.or using with create inline views of all defaults. 在subquery.or中或与create一起使用所有默认值的内联视图。 Then outer join to those defaults. 然后外部联接到那些默认值。

I first created a table called usr_test_table which has same data as mentioned above. 我首先创建了一个名为usr_test_table的表,该表具有与上述相同的数据。 And note that my database is oracle so do not get confused by "from dual". 并且请注意,我的数据库是oracle,所以请不要对“ from dual”感到困惑。 That is a special table in oracle with one row in one column. 那是oracle中的一个特殊表,每一行一行。

select t1.cust, t1.city, t1.country, t1.region,
       case 
           when t1.companyid is not null then t1.companyid
           else (
                   select max(companyid)
                   from usr_test_table t2
                   where t2.country = t1.country
               )
       end companyid
from usr_test_table t1

It is slightly simpler than earlier comment about outer join to an inline view. 它比之前关于外部连接到内联视图的注释要简单一些。 Since now databases allow a subquery in select clause such situatioins are simpler to handle that way. 由于现在数据库允许在select子句中使用子查询,因此这种情况更易于处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM