简体   繁体   English

考虑字符长度加入

[英]Join considering length of characters

I am trying to do a left join based on the number of characters. 我正在尝试根据字符数进行左连接。 In the destination_postal_code column I hace a more deailed postcode value. 在destination_postal_code列中,我使用了更为详细的邮政编码值。 In the dest_postal_code_prefix I have only the first few digits of a postcode. 在dest_postal_code_prefix中,我只有邮政编码的前几位。 When I join I would like to output to consider this: 当我加入时,我想输出以下内容:

destination_postal_code     dest_postal_code_prefix
2345                        23
3356                        33
5672                        567

For now I have : 现在我有:

SELECT DISTINCT 
p.destination_postal_code
FROM posimorders.atrops_ddl.o_slam_packages p
LEFT JOIN posimorders.sc_execution_eu.o_transit_time_pad t
ON p.destination_postal_code = t.dest_postal_code_prefix

The expected output would be 预期的输出将是

destination_postal_code 
2345                        
3356                        
5672                        

In the output it can be seen that, when my prefix is 23, I want all psotcodes begining with 23.. to be in mu output and so on 在输出中可以看到,当我的前缀为23时,我希望所有以23 ..开头的psotcode都在mu输出中,依此类推。

Maybe this, using the LIKE operator: 也许使用LIKE运算符:

SELECT DISTINCT 
p.destination_postal_code, t.dest_postal_code_prefix
FROM posimorders.atrops_ddl.o_slam_packages p
LEFT JOIN posimorders.sc_execution_eu.o_transit_time_pad t
ON p.destination_postal_code like t.dest_postal_code_prefix||'%';

If you have overlap, you might want to have the longest matches first: 如果有重叠,则可能要先获得最长的匹配项:

SELECT DISTINCT 
p.destination_postal_code, t.dest_postal_code_prefix
FROM posimorders.atrops_ddl.o_slam_packages p
LEFT JOIN posimorders.sc_execution_eu.o_transit_time_pad t
ON p.destination_postal_code like t.dest_postal_code_prefix||'%'
ORDER BY LENGTH(t.dest_postal_code_prefix) DESC
;

If your prefixes don't overlap, then you can just use LIKE : 如果您的前缀不重叠​​,则可以使用LIKE

SELECT DISTINCT p.destination_postal_code, t.dest_postal_code_prefix
FROM posimorders.atrops_ddl.o_slam_packages p LEFT JOIN
     posimorders.sc_execution_eu.o_transit_time_pad t
     ON p.destination_postal_code LIKE t.dest_postal_code_prefix || '%';

However, if they overlap (say "12" and "123"), then you probably want the longest one. 但是,如果它们重叠(例如“ 12”和“ 123”),则可能需要最长的一个。 In that case, use aggregation along with LIKE : 在这种情况下,请与LIKE一起使用聚合:

SELECT p.destination_postal_code, MAX(t.dest_postal_code_prefix) as dest_postal_code_prefix
FROM posimorders.atrops_ddl.o_slam_packages p LEFT JOIN
     posimorders.sc_execution_eu.o_transit_time_pad t
     ON p.destination_postal_code LIKE t.dest_postal_code_prefix || '%'
GROUP BY p.destination_postal_code;

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

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