如何避免多重联接

问题描述

我有以下代码。为了获得cost_center,我必须进行2次连接-首先在billing_area_id和facility_id的组合上,如果没有匹配项,我必须在billing_area_id上进行连接才能得到它。我想为cost_center设计一个维度,该维度应满足这种情况,以便仅一次连接就足够了。如果您有任何想法请告诉我

select COALESCE(cs1.cost_center,cs2.cost_center) cost_center
from fact_invoice i
inner join dim_facility f on i.hospital_id = f.id 
left join lookup_billingarea_to_wd_costcenter cs1 on i.billing_area_id = cs1.billing_area_id and COALESCE (i.hospital_id,0) = cs1.facility_id
left join lookup_billingarea_to_wd_costcenter cs2 on i.billing_area_id = cs2.billing_area_id and (cs1.cost_center IS NULL and cs2.facility_id=0)

为澄清而添加 对于不提供数据,我深表歉意。一个billing_area_id可以具有多个facility_id和0个记录的facility_id。但是对我来说,挑战是,在某些情况下,我们无法获得匹配的afility_id,在这种情况下,我们只需要记录设施ID为0的情况即可。对于前,请参阅下面 可以说我们有

Billing_area_id Facility_id cost_center
1   0   abc
1   3   acd
2   0   abd
2   1   ghf
2   2   hgf

如果我输入Billing_area_id = 1和Facility_id = 2(该组合在查找表中不存在),那么我需要获取“ abc”作为成本中心

解决方法

您可以创建一个执行联接的视图,然后在多个位置使用该视图:

CREATE VIEW lookup_billingarea_to_wd_costcenter_with_default AS
SELECT 
  cs1.billing_area_id,cs1.facility_id,COALESCE(cs1.cost_center,cs2.cost_center) as cost_center
FROM
  lookup_billingarea_to_wd_costcenter cs1
  INNER JOIN lookup_billingarea_to_wd_costcenter cs2
  ON 
    cs1.billing_area_id = cs2.billing_area_id AND
    cs2.billing_area_id = 0

请注意,您没有为此发布任何示例数据,因此可以猜测,对于每个billing_area_id,您的N设施ID都不为零,并且还有一个设施ID为0的行。如果没有的话,有时没有零行,则需要退出加入cs2

您将以如下方式使用它:

select COALESCE(cs1.cost_center,cs2.cost_center) cost_center
from fact_invoice i
inner join dim_facility f on i.hospital_id = f.id 
inner join lookup_billingarea_to_wd_costcenter_with_default cs 
ON i.billing_area_id = cs.billing_area_id AND COALESCE(i.hospital_id,0) = cs.facility_id

如果在任何情况下都没有成本中心,则需要退出视图