SQL 中的复杂 INSERT INTO SELECT 语句

Complex INSERT INTO SELECT statement in SQL

我在 SQL 中有两个 table。我需要将行从一个 table 添加到另一个。我添加行的 table 看起来像:

timestamp, deviceID, value

2020-10-04, 1, 0
2020-10-04, 2, 0
2020-10-07, 1, 1
2020-10-08, 2, 1

但是,如果特定设备 ID 的状态与上一个时间戳相比发生了变化,我必须在此 table 添加一行。

例如,不会添加此记录“2020-10-09、2、1”,因为 deviceID = 2 和最后一个时间戳 =“2020-10-08”的值未更改。同时记录 "2020-10-09, 1, 0" 将被添加,因为 deviceID = 1 的值已更改为 0.

我在为此逻辑编写查询时遇到问题。我写过这样的东西:

insert into output
select *
from values
where value != (
select value
from output
where timestamp = (select max(timestamp) from output) and output.deviceID = values.deviceID)

当然不行,因为查询的最后一部分是“and output.deviceID = values.deviceID”。 实际上,问题是我不知道如何从“输出”table 中获取值,其中 deviceID 与我尝试插入的行中的相同。

我会使用 order by 和一些东西来限制一行:

insert into output
    select *
    from values
    where value <> (select o2.value
                    from output o2
                    where o2.deviceId = v.deviceId
                    order by o2.timestamp desc
                    fetch first 1 row only
                   );

以上为标准SQL。特定的数据库可能有其他的表达方式,比如limittop (1).