我想要查询是否可以使用相同的表将值分成不同的列
所以这是我的示例表:
从表格中选择日期,工具,价值
+----------------------+-----------+-------+
| date | tool | value |
| | | |
| 2017-03-11 13:03:38 | machineA | 14 |
| 2017-03-11 13:03:39 | machineA | 18 |
| 2017-03-11 13:03:40 | machineB | 50 |
| 2017-03-11 13:03:41 | machineB | 50 |
+----------------------+-----------+-------+
尝试输出如下: 在我的代码中,我循环此查询然后放入数据集然后重新组织值,但是现在我不确定哪个函数在此查询上是可靠的,如果我需要进行连接或联合或具有某些条件。
+----------------------+-----------+----------+
| date | machineA | machineB |
| | | |
| 2017-03-11 13:03:38 | 14 | 0 |
| 2017-03-11 13:03:39 | 18 | 0 |
| 2017-03-11 13:03:40 | 0 | 50 |
| 2017-03-11 13:03:41 | 0 | 50 |
+----------------------+-----------+----------+
提前感谢任何建议和建议。
答案 0 :(得分:1)
尝试以下查询,我创建了一个表t02
,您可能有另一个名称,只需将其更改为您的名称。
mysql> select * from t02;
+---------------------+----------+-------+
| date | tool | value |
+---------------------+----------+-------+
| 2017-03-11 13:03:39 | machineB | 50 |
| 2017-03-11 13:03:41 | machineB | 50 |
| 2017-03-11 13:03:41 | machineA | 14 |
| 2017-03-11 13:03:42 | machineA | 18 |
+---------------------+----------+-------+
让我告诉你如何一步一步地做,首先让我们去拿一个!
select date, (tool='machineA') as machineA, (tool='machineB') as machineB from t02;
+---------------------+----------+----------+
| date | machineA | machineB |
+---------------------+----------+----------+
| 2017-03-11 13:03:39 | 0 | 1 |
| 2017-03-11 13:03:41 | 0 | 1 |
| 2017-03-11 13:03:41 | 1 | 0 |
| 2017-03-11 13:03:42 | 1 | 0 |
+---------------------+----------+----------+
select date, if((tool='machineA'), value, 0) as machineA, if((tool='machineB'), value, 0) as machineB from t02;
然后你应该得到以下结果:
+---------------------+----------+----------+
| date | machineA | machineB |
+---------------------+----------+----------+
| 2017-03-11 13:03:39 | 0 | 50 |
| 2017-03-11 13:03:41 | 0 | 50 |
| 2017-03-11 13:03:41 | 14 | 0 |
| 2017-03-11 13:03:42 | 18 | 0 |
+---------------------+----------+----------+
如果您有machineC
和machineD
等,那么您只需按照同样的方式进行if((tool='machineX'), value, 0) as machineX