Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
sql查询,用于检查表中的2条记录是否更改了特定值_Sql_Date_Greatest N Per Group_Window Functions - Fatal编程技术网

sql查询,用于检查表中的2条记录是否更改了特定值

sql查询,用于检查表中的2条记录是否更改了特定值,sql,date,greatest-n-per-group,window-functions,Sql,Date,Greatest N Per Group,Window Functions,我有一个表,其中包含以下数据: Date, Id, hash, Timestamp ---- -- ------ --------- 2020-05-21 001 abc123 07:00am 2020-05-21 001 abc123 08:00am 2020-05-21 001 def456 09:00am 2020-05-21 002

我有一个表,其中包含以下数据:

Date,         Id,      hash,      Timestamp
----          --       ------     ---------
2020-05-21    001      abc123     07:00am
2020-05-21    001      abc123     08:00am
2020-05-21    001      def456     09:00am
2020-05-21    002      dddddd     07:00am
2020-05-21    002      dddddd     08:00am
2020-05-21    002      dddddd     09:00am
2020-05-21    003      222222     07:00am
2020-05-21    003      qqqwww     08:00am
2020-05-21    003      qqqwww     09:00am

我需要一个查询,该查询将检查最新记录9am记录,并将其与为该id 8am记录插入的先前记录进行比较,并检查哈希值是否不同。我只想要一个上午9点的记录列表,这些记录的哈希值已更改。提前谢谢

如果您的数据库支持,您可以使用窗口函数:

select t.*
from (
    select
        t.*,
        row_number() over(partition by id order by timestamp desc) rn,
        lag(hash)    over(partition by id order by timestamp) lag_hash
    from mytable t
) t
where rn = 1 and hash <> lag_hash

这假设时间戳列的数据类型类似于日期,或者至少可以使用中的数据类型对记录进行正确排序。

请使用您正在使用的数据库标记您的问题:mysql、oracle、postgresql。。。?