检测历史记录中特定列的变化 table

Detecting the change on the certain column in the history table

考虑以下数据:

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 table,我将所有更改保存在某个 table 中。 现在我需要获取 col1 列中 data 的每个当前条目的最后更改日期。 在那种情况下,所需的输出应该是

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
)

如您所见,现在我只是获取最后一次记录更改的日期,而不管更改发生在哪一列。

谁能帮我解决这个问题?

您可以使用 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

每个 data_id 只有一个成员的组需要 prev_col1 is null 条件,并假定第一个成员符合更改条件。

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

您可以使用以下查询:

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_idlast col1 值:

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

使用上面的查询作为派生 table 您可以重新连接到原始 table 以获得每个组的 最早 日期:

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 

注:查询也会returndata_id组相关只有一个col1 价值。您需要稍微更改查询以过滤掉这些行,以防您不需要它们。

Demo here