jquery - 如何将查询结果合并为新列?
问题描述
我有一张表,其中包含 200 个不同的传感器和相应的传感器值。我想创建一个查询,其中不同的传感器值位于不同的列中。
我已经尝试过加入和联合,它没有按预期提供。
从测量值中选择 *;// 简化
| 传感器 ID | 价值 |
| 6 | 110 |
| 6 | 120 |
| 6 | 180 |
| 8 | 250 |
| 8 | 280 |
| 8 | 290 |
目标
| 传感器6 | 传感器8|
| 110 | 250 |
| 120 | 280 |
| 180 | 290 |
PS:传感器的行总是相等的。表中还有时间戳列。我认为放在这里无关紧要。
解决方案
我的解决方案基于这样的想法,即有一个排名来表示传感器值。测试它的数据
CREATE TABLE table1
(`sensorId` int, `Value` int)
;
INSERT INTO table1
(`sensorId`, `Value`)
VALUES
(6, 110),
(6, 120),
(6, 180),
(8, 250),
(8, 280),
(8, 290),
(9, 250),
(9, 280),
(9, 290)
;
然后我使用了这个查询
Select Value6,Value8,Value9
From
(SELECT Value as Value6,
@curRank := @curRank + 1 AS rank
FROM table1 t1, (SELECT @curRank := 0) r
Where sensorId =6
ORDER BY Value) t1
inner join
(SELECT Value as Value8,
@curRank2 := @curRank2 + 1 AS rank
FROM table1 t2, (SELECT @curRank2 := 0) r
Where sensorId =8
ORDER BY Value) t2 on t1.rank = t2.rank
inner join
(SELECT Value as Value9,
@curRank3 := @curRank3 + 1 AS rank
FROM table1 t2, (SELECT @curRank3 := 0) r
Where sensorId =9
ORDER BY Value) t3 on t1.rank = t3.rank;
结果
Value6 Value8 Value9
110 250 250
120 280 280
180 290 290
这依赖于每个 sensorId 始终有相同数量的行。这也可以在存储过程中使用,就像我在这里完成的, 如何在 mysql 中动态地将行值设置为列 但是在这里你不需要游标,只需要从 1 到 200 的循环。
老实说,我会使用一个 select * From table1 order By SensorId, Value,并在 jquer.success 中使用结果。
推荐阅读
- java - 如何通过单击 JDialog (JAVA) 上的按钮来更新 JInternalFrame
- sql - 转置 SQL 结果集中的行/列
- http - 如何在 tomcat 配置上添加内容安全策略
- ios - 发生崩溃但在 Firebase Crashlytics 中显示错误/旧版本号
- php - PDF 文件中的内部链接,即合并,当链接和目标在合并之前位于不同的 PDF 文件中时
- mysql - 编写此查询的正确方法是什么?
- php - SimpleSAMLPHP:成功登录后,getAttribute 不会从 IdP 重新调整任何内容
- python - 使用 HMM 模型对具有 5 天“回溯”的每日收益时间序列状态进行分类
- jmeter - 从先前的响应中提取值并在 jmeter 的后续请求中以相应数量的块发送数据
- javascript - 下拉菜单应该关闭了,除了主页面,怎么办?