2017-08-15 136 views
2

考慮以下數據上該特定列的變化:檢測的歷史記錄表

history.data 
======================================= 
id |data_id| col1 | col2 | date 
---+-------+-------+-------+----------- 
1 |1  | 123 | 321 | 2017-08-01 
2 |1  | 124 | 321 | 2017-08-03 
3 |2  | 222 | 555 | 2017-08-05 
4 |2  | 242 | 555 | 2017-08-07 
5 |2  | 242 | 333 | 2017-08-11 

所以這是history_data表,我保持一定的表中的所有變化。 現在我需要獲取data的每個當前條目在col1列中的最後更改的日期。 在這種情況下所需的輸出應該是

data_id | date 
--------+----------- 
1  | 2017-08-03 
2  | 2017-08-07 

我需要這樣做在以下方面:

with cte1 as (
    select distinct on(data_id) 
    data_id, 
    date::date 

    from data d 
    join history.data hd on hd.data_id = d.id 
    order by d.id, hd.date desc 
) 

因此,大家可以看到,現在我正準備最後的日期記錄更改,而不考慮發生更改的列。

任何人都可以請幫助我嗎?

+0

爲什麼對'data_id = 2'您預計日期'2017-08-07',而不是'2017-08-11'? –

+0

@OtoShavadze,因爲'2017-08-11'上的變化發生在'col2'上,但我只對'col1'上的變化感興趣。 –

回答

2

您可以使用lag()獲得以前prev_col1價值和prev_col1 <> col1其識別發生更改的所有行:

select distinct on(data_id) * from (
    select lag(col1) over (partition by data_id order by d.id) prev_col1, 
    d.id, 
    col1, 
    data_id, 
    date::date 
    from data d 
    join history.data hd on hd.data_id = d.id 
) t where prev_col1 <> col1 or prev_col1 is null 
order by id desc 

需要的prev_col1 is null條件組只有1名成員每data_id並假定第一成員資格作爲變化。

1
select data_id, max(mindt) from (
    select data_id, col1, min(date) as mindt 
    from history_data 
    group by data_id, col1 
) t 
group by data_id 
1

您可以使用下面的查詢:

select distinct on(data_id) 
     data_id, 
     col1 
from data d 
join history_data hd on d.id = hd.data_id 
order by data_id, date desc; 

得到每data_id最後col1值:

data_id col1 
------------- 
1 124 
2 242 

使用上述查詢作爲派生表,您可以加入回到原來的表格,得到最早的每個gro的日期達:

select t1.data_id, t1.col1, min(date::date) 
from history_data t1 
join (
    select distinct on(data_id) 
      data_id, 
      col1 
    from data d 
    join history_data hd on d.id = hd.data_id 
    order by data_id, date desc 
) t2 on t1.data_id = t2.data_id and t1.col1 = t2.col1 
group by t1.data_id, t1.col1; 

輸出:

data_id col1 min 
--------------------------- 
1  124  03.08.2017 
2  242  07.08.2017 

注:查詢也將返回data_id相關只是一個col1值組。您需要稍微更改查詢以過濾這些行,以防您不需要它們。

Demo here