PostgreSQL连接数据区域上的表

mgdq6dx1  于 2023-10-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(112)

在PostreSQL中,我正在尝试连接以下表:
| ID|从|到|颜色|形状|
| --|--|--|--|--|
| 1 |2020-09-01 10:05:31.510| 2021-09-13 16:40:27.000|红色||
| 1 |2021-09-13 16:40:27.000| 2022-07-01 14:34:53.728|红色|平方|
| 1 |2022-07-01 14:34:53.728| 2019 -12- 21 00:00:00|红色|圈|
| ID|从|信|
| --|--|--|
| 1 |2021-04-01 00:00:00.000|一|
| 1 |2019 -06- 21 00:00:00| B|
| 1 |2019 - 01 - 22 00:00:00| C|
| 1 |2019 -01 -12 00:00:00| D|
第二个表没有有效的to,该记录是有效的,直到插入一个具有更大From的新记录。
预期输出如下表所示:
| ID|从|到|颜色|形状|信|
| --|--|--|--|--|--|
| 1 |2020-09-01 10:05:31.510| 2021-04-01 00:00:00.000|红色|||
| 1 |2021-04-01 00:00:00.000| 2021-09-13 16:40:27.000|红色||一|
| 1 |2021-09-13 16:40:27.000| 2019 -06- 21 00:00:00|红色|平方||
| 1 |2019 -06- 21 00:00:00| 2022-07-01 14:34:53.728|红色|平方|B|
| 1 |2022-07-01 14:34:53.728| 2019 - 01 - 22 00:00:00|蓝色|圈||
| 1 |2019 - 01 - 22 00:00:00| 2019 -01 -12 00:00:00|绿色|圈|C|
| 1 |2019 -01 -12 00:00:00| 2019 -12- 21 00:00:00|绿色|圈|D|
我尝试在ID和B.From之间使用完全联接,但无法修复新记录的From和To日期。
任何输入是赞赏,谢谢!

cigdeys3

cigdeys31#

我认为你可以使用left join和lead函数来得到你想要的输出。
举例说明:

WITH Combined AS (
  SELECT
    a.ID,
    a."From" AS a_from,
    COALESCE(b."From", a."To") AS a_to,
    a.Color,
    a.Shape,
    b."Letter"
  FROM table1 a
  LEFT JOIN (
    SELECT
      "ID",
      "From",
      "Letter",
      LEAD("From") OVER (PARTITION BY "ID" ORDER BY "From") AS next_from
    FROM table2
  ) b
  ON a.ID = b.ID AND (a."To" > b."From" OR a."To" = b.next_from)
)

SELECT
  ID,
  a_from AS "From",
  a_to AS "To",
  Color,
  Shape,
  "Letter"
FROM Combined
ORDER BY a_from;

相关问题