sql:按顺序选择任何更改的第一行

时间:2018-10-19 13:33:51

标签: sql postgresql-9.4 zabbix

您好,我想在postgres上执行以下任务

我有这个要求:

select to_timestamp(clock), value
from history_str
where itemid =696857
order by clock desc

返回以下内容:

enter image description here

我想按钟表先出现列表顺序。

然后我期望的结果是带有时间戳和值的1到8。

我尝试了over函数,但无法正确完成它。

有什么帮助吗?谢谢

2 个答案:

答案 0 :(得分:1)

一种方法使用ROW_NUMBER

SELECT ts, value
FROM
(
    SELECT TO_TIMESTAMP(clock) AS ts, value,
        ROW_NUMBER() OVER (PARTITION BY value ORDER BY TO_TIMESTAMP(clock) DESC) rn
    FROM history_str
) t
WHERE rn = 1;

答案 1 :(得分:0)

您要为此使用lag(),因为value可以改回以前的值:

select to_timestamp(clock), value
from (select t.*,
             lag(value) over (partition by itemid order by to_timestamp(clock)) as prev_value
      from t
      where itemid = 696857
     ) t
where prev_value is null or prev_value <> value
order by clock desc;