首页 > 解决方案 > SQL 中的复杂 INSERT INTO SELECT 语句

问题描述

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

timestamp, deviceID, value

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

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

例如,不会添加此记录“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”,它不起作用。实际上问题是我不知道如何从“输出”表中获取值,其中 deviceID 与我尝试插入的行中的值相同。

标签: sqlinsertsql-insert

解决方案


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


推荐阅读