[英]How to use a CASE statement with a JOIN
I am trying to use join statement that vary based on certain case statements. 我正在尝试使用基于某些case语句而有所不同的join语句。 When the field lane.dest_postal_code_prefix is NOT NULL then I want the join to be like the first block of code below.
当字段lane.dest_postal_code_prefix不为NULL时,我希望联接像下面的第一段代码一样。 When the field lane.dest_postal_code_prefix is NULL then I want the join to be like second block of code below.
当field lane.dest_postal_code_prefix为NULL时,我希望联接像下面的第二个代码块一样。 (Note the difference on the ON conditions between the two cases)
(请注意两种情况下ON条件的差异)
I need some help adding the case statement to the join clause. 我需要一些帮助,将case语句添加到join子句中。
--WHEN lane.dest_postal_code_prefix is NOT NULL
SELECT * FROM big_bucket_bridge A
LEFT JOIN lane
ON
(
A.customer_country = lane.dest_country_code
AND
SUBSTRING( A.ddm_zip, 1, LENGTH( lane.dest_postal_code_prefix ) ) =
lane.dest_postal_code_prefix
)
WHERE
snapshot_day between '2019-06-23'-22 and '2019-06-23'
AND (is_before_cutoff_g OR (is_before_cutoff_opt_g and not under_two))
AND row_n =1
;
--WHEN lane.dest_postal_code_prefix is NULL
SELECT * FROM big_bucket_bridge A
LEFT JOIN lane
ON
(
A.customer_country = lane.dest_country_code
)
WHERE
snapshot_day between '2019-06-23'-22 and '2019-06-23'
AND (is_before_cutoff_g OR (is_before_cutoff_opt_g and not under_two))
AND row_n =1
;
You can use one ON clause like this: 您可以这样使用一个ON子句:
ON
(
A.customer_country = lane.dest_country_code
AND
COALESCE(SUBSTRING(A.ddm_zip, 1, LENGTH( lane.dest_postal_code_prefix )), '') = CASE
WHEN lane.dest_postal_code_prefix IS NOT NULL THEN lane.dest_postal_code_prefix
ELSE COALESCE(SUBSTRING(A.ddm_zip, 1, LENGTH( lane.dest_postal_code_prefix )), '')
END
)
In the 2nd case (else part) the condition is always true because it is: 在第二种情况下(其他部分),该条件始终为真,因为它是:
COALESCE(SUBSTRING(A.ddm_zip, 1, LENGTH( lane.dest_postal_code_prefix )), '') = COALESCE(SUBSTRING(A.ddm_zip, 1, LENGTH( lane.dest_postal_code_prefix )), '')
so the only actual condition is 所以唯一的实际情况是
A.customer_country = lane.dest_country_code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.