Postgresql postgres中的完全外部连接

Postgresql postgres中的完全外部连接,postgresql,join,union,outer-join,full-outer-join,Postgresql,Join,Union,Outer Join,Full Outer Join,我在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

我在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
尝试的查询没有提供结果。我还尝试过使用循环select语句。

您需要一个
完全外部联接。
()。
由于潜在的
NULL
值,您无法使用
WHERE
过滤器,因此必须使用
CTE
s()对这两个数据集进行预过滤

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

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