sql - 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 与我尝试插入的行中的值相同。
解决方案
我会使用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。特定的数据库可能有其他方式来表达这一点,例如limit
或top (1)
。
推荐阅读
- c++ - 将 QFont styleName 转换为样式表
- python - 在python中读取json文件
- azure - 无法在从 Azure Monitor 工作簿创建的 Azure 仪表板(所有用户)中设置默认时间范围
- linear-algebra - 当寻找具有一组(非零)容差的矩阵内核时,你怎么称呼它?
- java - kyotocabinet 数据库 - RSS 无限增加
- node.js - 通过 mongoose 检索和保存数据到 mongodb 的最有效方法
- javascript - 如果其中一个被拒绝,如何拒绝所有的承诺
- android - 拥有多个支持 OpenCV 的 JNI 库
- ruby-on-rails - ActiveStorage gem 不是最新的?
- angular - 拆分视图未按预期工作,未应用样式