首页 > 解决方案 > 如何将查询结果合并为新列?

问题描述

我有一张表,其中包含 200 个不同的传感器和相应的传感器值。我想创建一个查询,其中不同的传感器值位于不同的列中。

我已经尝试过加入和联合,它没有按预期提供。

从测量值中选择 *;// 简化


| 传感器 ID | 价值 |

| 6 | 110 |

| 6 | 120 |

| 6 | 180 |

| 8 | 250 |

| 8 | 280 |

| 8 | 290 |


目标


| 传感器6 | 传感器8|

| 110 | 250 |

| 120 | 280 |

| 180 | 290 |


PS:传感器的行总是相等的。表中还有时间戳列。我认为放在这里无关紧要。

标签: jquerymysqlsql

解决方案


我的解决方案基于这样的想法,即有一个排名来表示传感器值。测试它的数据

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 中使用结果。


推荐阅读