SQL中的复杂INSERT INTO SELECT语句

时间:2020-10-04 16:14:04

标签: sql insert sql-insert

我在SQL中有两个表。我需要将一个表中的行添加到另一个表中。我向其中添加行的表如下所示:

timestamp, deviceID, value

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

但是,如果与上一个时间戳相比,特定deviceID的状态发生了更改,我必须在此表中添加一行。

例如,将不会添加此记录“ 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)

当然,由于查询的最后一部分“和output.deviceID = values.deviceID”,所以它不起作用。 实际上,问题是我不知道如何从“输出”表中获取值,其中deviceID与我尝试插入的行中的设备ID相同。

1 个答案:

答案 0 :(得分:0)

我会使用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)

相关问题