【问题标题】:How to merge two tables to show entries historical changes如何合并两个表以显示条目历史更改
【发布时间】:2022-01-27 18:20:21
【问题描述】:

我有两张桌子

T1

ID Reference Status Event Timestamp
1 Flowers Dispatched 2021-12-10
2 Flowers Delivered 2021-12-11

T2

ID Reference Comments Event Timestamp
1 Flowers well done 2021-12-12
2 Flowers go on 2021-12-13
3 Pot random 2021-12-13

我试图通过查询 Flowers 参考的表格是(使用 Postgres)

t1_ID t2_ID Reference Comments Status t1_Event Timestamp t2_Event Timestamp
1 null Flowers null Dispatched 2021-12-10 null
2 null Flowers null Delivered 2021-12-11 null
null 1 Flowers well done Delivered 2021-12-11 2021-12-12
null 2 Flowers go on Delivered 2021-12-11 2021-12-13

换句话说,我需要一个连接表来记录两个表之间的所有更新。
我尝试了许多查询,例如 LEFT JOIN、UNION 等,但所有尝试均不成功。

您能否建议我应该使用哪些 SQL 语句来获得预期的结果?

【问题讨论】:

  • 您到底想做什么?只需将两个表中所有 Flowers 引用的结果显示在一个表中?
  • 没错,但是如果我使用简单的 JOIN,它将不会返回 Comments 为空的行。
  • @RDK 为什么 t1_id = 2 表示来自 T2 的行?不应该是NULL吗?
  • @Blue_Elephant 基本上对于每个 T1 行,我需要检查 T2 中是否有一个具有相同引用和 LOWER-EQUAL T2_event 时间戳的条目
  • @Zakaria 你是对的,我编辑了它。

标签: sql postgresql


【解决方案1】:

使用 cte 和 union

with cte as(
   select ID as t1_ID,
          null as t2_ID,
          Reference,
          null as Comments,
          Status,
          Event_Timestamp as t1_Event_Timestamp,
          null as t2_Event_Timestamp,
          row_number() over(partition by Reference order by Reference) seq
    from t1
)

select t1_id,t2_id,reference,comments,status,t1_event_timestamp,t2_event_timestamp  
from cte

union all

select null as t1_ID,
       t2.ID::varchar(10) as t2_ID,
       t2.Reference,
       Comments,
       (select max(Status) from cte t3 where t3.seq = (select max(seq) from cte)) as status,
       (select max(t1_Event_Timestamp) from cte t3 where t3.Reference = t2.Reference) as t1_Event_Timestamp,
       t2.Event_Timestamp as t2_Event_Timestamp
from t1
left join t2 on t1.Reference = t2.Reference
group by t2.ID,t2.Reference,t2.Comments,t2.Event_Timestamp

db<>fiddle中的演示

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 2011-06-28
    相关资源
    最近更新 更多