sql—如何在多个联接中获取联接列

ntjbwcob  于 2021-06-02  发布在  Hadoop
关注(0)|答案(1)|浏览(352)

我正在尝试联接多个表(总共11个表),并希望将case\u id列合并为最终联接结果。
帐户可以是主保险、次保险和/或两者。
当我运行下面的查询时,我只从join“k”获得case\ id。如何从join“k”和“l”中查询到case\u id?我用的是claudera hadoop。
例如,我有下面的简化版本:

SELECT DISTINCT a1.id AS Account_Id,
    k.Case_Id,
    k.Primary_Insurance_Payer_Name,
    l.Secondary_Insurance_Payer_Name
    FROM account a1 left outer JOIN  
    (
      SELECT k3.Name AS Primary_Insurance_Payer_Name,
      k3.Id AS Account_Id,
      k4.Id as Case_Id
      FROM patient k1
      JOIN patient_insurance k2
      ON k1.A360_Primary_Insurance__c=k2.Id
      JOIN account k3
      ON k2.A360_Payer__c=k3.Id
      left outer join pep_case k4
      on k4.enrolled_patient__c=k1.id     
    ) k ON a1.id=k.Account_Id left outer JOIN 
    (
      SELECT l3.Name AS Secondary_Insurance_Payer_Name,
      l3.Id AS Account_Id,
      l4.Id as Case_Id
      FROM patient l1
      JOIN patient_insurance l2
      ON l1.A360_Secondary_Insurance__c=l2.Id
      JOIN account l3
      ON l2.A360_Payer__c=l3.Id
      left outer join pep_case l4
      on l4.enrolled_patient__c=l1.id) l ON a1.id=l.Account_Id
huwehgph

huwehgph1#

执行与处理保险付款人名称类似的操作,在子查询中为其指定不同的别名,然后在最后的select子句中引用这些别名

SELECT DISTINCT
      a1.id AS Account_Id
    , k.k_Case_Id
    , l.l_Case_Id
    , k.Primary_Insurance_Payer_Name
    , l.Secondary_Insurance_Payer_Name
FROM account a1
LEFT OUTER JOIN (
      SELECT
            k3.Name AS Primary_Insurance_Payer_Name
          , k3.Id   AS Account_Id
          , k4.Id   AS k_Case_Id
      FROM patient k1
      JOIN patient_insurance k2 ON k1.A360_Primary_Insurance__c = k2.Id
      JOIN account k3 ON k2.A360_Payer__c = k3.Id
      LEFT OUTER JOIN pep_case k4 ON k4.enrolled_patient__c = k1.id
) k ON a1.id = k.Account_Id
LEFT OUTER JOIN (
      SELECT
            l3.Name AS Secondary_Insurance_Payer_Name
          , l3.Id   AS Account_Id
          , l4.Id   AS l_Case_Id
      FROM patient l1
      JOIN patient_insurance l2 ON l1.A360_Secondary_Insurance__c = l2.Id
      JOIN account l3 ON l2.A360_Payer__c = l3.Id
      LEFT OUTER JOIN pep_case l4 ON l4.enrolled_patient__c = l1.id
) l ON a1.id = l.Account_Id
WHERE k_Case_Id  = l_Case_Id

编辑

一个单独的select查询可以将保险信息连接两次(请参阅别名ppi和spi)。注:我还把join改成了 patientpep_case 进入内部连接。

SELECT
      pac.Name AS Primary_Insurance_Payer_Name
    , sac.Name AS Secondary_Insurance_Payer_Name
    , pac.Id   AS Account_Id
    , pc.Id    AS Case_Id
FROM patient p
INNER JOIN pep_case pc           ON p.id = pc.enrolled_patient__c
INNER JOIN patient_insurance ppi ON p.A360_Primary_Insurance__c = ppi.Id
INNER JOIN account pac           ON ppi.A360_Payer__c = pac.Id
LEFT  JOIN patient_insurance spi ON p.A360_Secondary_Insurance__c = spi.Id
LEFT  JOIN account sac           ON spi.A360_Payer__c = sac.Id

相关问题