2017-08-15 135 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