【问题标题】:Full outer join in postgrespostgres中的完全外连接
【发布时间】:2018-10-20 14:20:33
【问题描述】:

我在 Postgresql 中有下表:

sch_code   sch_level   start_date   end_date      flag
1234          P        01-01-2018   31-01-2018    V
1234          S        01-01-2018   31-01-2018    V
5678          S        01-01-2018   31-01-2018    V
8965          P        01-01-2018   31-01-2018    V

我需要的结果如下。

sch_code    start_P         end_P     start_S     end_S
1234        01-01-2018   31-01-2018   01-01-2018   31-01-2018  
5678        00-00-0000   00-00-0000   01-01-2018   31-01-2018  
8965        01-01-2018   31-01-2018   00-00-0000   00-00-0000  

我用UNION 尝试的查询没有提供结果。我也尝试过使用循环选择语句。

【问题讨论】:

    标签: postgresql join union outer-join full-outer-join


    【解决方案1】:

    您需要FULL OUTER JOIN (see guide here)。
    由于潜在的NULL 值,您不能使用WHERE 过滤器,因此您必须使用CTEs (see guide here) 预过滤这两个数据集。

    WITH pdata AS (
      SELECT * FROM mytable WHERE sch_level='P'
    ),
    sdata AS (
      SELECT * FROM mytable WHERE sch_level='S'
    )
    SELECT
      COALESCE(pdata.sch_code, sdata.sch_code) AS sch_code,
      pdata.start_date AS start_P,
      pdata.end_date   AS end_P,
      sdata.start_date AS start_S,
      pdata.end_date   AS end_S
    FROM pdata
    FULL OUTER JOIN sdata ON pdata.sch_code = sdata.sch_code
    

    如果您不想在日期字段中使用 NULL 值,只需使用 COALESCE 并提供您可能使用的任何数据类型的默认值。

    【讨论】:

      猜你喜欢
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 2013-03-11
      • 2022-01-01
      相关资源
      最近更新 更多