簡體   English   中英

如何從三個單獨的表中構建一個事件表,以顯示隨時間的增量變化?

[英]How do I build an events table from three separate tables showing incremental change over time?

我正在嘗試構建一個數據集,以顯示某些產品屬性隨時間的增量變化。 數據位於 AWS Athena 中的三個獨立表中,每個表存儲不同的屬性,並且可以在不同時間獨立更新。 tbl1可以連接到tbl2並且tbl2可以連接到tbl3 表之間始終存在一對一的關系,因此在此示例中tbl1.id=1只會與tbl2.id=2相關,而tbl2.id=2只會與tbl3.id=3相關:

tbl1
| id | updated_at       | bool  |
| 1  | 2019-09-10 06:00 | True  |
| 1  | 2020-08-05 10:00 | False |
| 1  | 2020-09-03 15:00 | True  |

tbl2
| id | tbl1_id | updated_at       | desc    |
| 2  | 1       | 2019-09-10 06:00 | thing 1 |

tbl3
| id | tbl2_id | updated_at       | value |
| 3  | 2       | 2019-09-10 06:00 | 100   |
| 3  | 2       | 2019-09-19 09:00 | 50    |
| 3  | 2       | 2019-12-02 11:00 | 20    |

我正在嘗試編寫一個查詢,將這些數據連接到一個表中,並且每個增量更新都有一行。 從上表中可以看出,在 2019 年 9 月 10 日進行了初始插入,然后在tbl1tbl3中進行了其他四項更改,因此最終應為五行,如下所示:

| tbl1_id | tbl1_updated_at  | bool  | tbl2_id | tbl2_updated_at  | desc   | tbl3_id | tbl3_updated_at  | value |
| 1       | 2019-09-10 06:00 | True  | 2       | 2019-09-10 06:00 | thing1 | 3       | 2019-09-10 06:00 | 100   |
| 1       | 2019-09-10 06:00 | True  | 2       | 2019-09-10 06:00 | thing1 | 3       | 2019-09-19 09:00 | 50    |
| 1       | 2019-09-10 06:00 | True  | 2       | 2019-09-10 06:00 | thing1 | 3       | 2019-12-02 11:00 | 20    |
| 1       | 2020-08-05 10:00 | False | 2       | 2019-09-10 06:00 | thing1 | 3       | 2019-12-02 11:00 | 20    |
| 1       | 2020-09-03 15:00 | True  | 2       | 2019-09-10 06:00 | thing1 | 3       | 2019-12-02 11:00 | 20    |

我從將所有內容連接在一起並使用一些WHERE子句的想法開始,例如:

select
*
from
tbl1
left join tbl2 on tbl1.id = tbl2.tbl1_id
left join tbl3 on tbl2.id = tbl3.tbl2_id
where
???

但無法讓它工作,也不確定這是否會奏效。 也許有某種 window 函數可以做到這一點? 感覺應該可以在 SQL 中做到這一點,但經過兩天的嘗試,我完全不知道該怎么做!

這是相當復雜的。 如果您在所有表中都有tbl1 id,那會更簡單。

無論如何,我們的想法是將union all列與tbl1 id 和updated_at結合在一起。 然后聚合,所以每個iddate有一行。

最后,使用帶有ignore nulls選項的last_value()來獲取填充的最新值:

with t as (
      select id, updated_at, max(bool) as bool, max(descr) as descr, max(value) as value
      from (select tbl1.id, tbl1.updated_at, tbl1.bool, null as descr, null as value
            from tbl1 
            union all
            select tbl2.tbl1_id, tbl2.updated_at, null, tbl2.descr, null
            from tbl2
            union all
            select tbl2.tbl1_id, tbl2.updated_at, null, null, tbl3.value
            from tbl2 join
                 tbl3
                 on tbl2.id = tbl3.tbl2_id
           ) t
     group by id, updated_at
    )
select id, updated_at,
       last_value(bool ignore nulls) over (partition by id order by updated_at) as bool,
       last_value(descr ignore nulls) over (partition by id order by updated_at) as descr,
       last_value(value ignore nulls) over (partition by id order by updated_at) as value
from t;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM