根据id列中的值将一个sql列转换为两个

时间:2018-06-08 15:30:19

标签: mysql sql

我有一个存储位置和速度值的MySQL数据库。但是,这两个值存储在单个列中,并由另一行中的id标记标识。

tagid    value    t_stamp
1        14.5     sometime1
1        13.5     sometime2
2        45.9     sometime1
2        32.8     sometime2

在这种情况下,tagid为1的值为position,tagid为2的值为velocity。我想把这两个分开来做一个这样的表:

position    velocity    time 
14.5        45.9        sometime1
13.5        32.8        sometime2

我是SQL Querying的新手,所以任何帮助都会受到赞赏。感谢

2 个答案:

答案 0 :(得分:1)

您可以在此处执行conditional聚合:

select max(case when tagid = 1 then value end) as position,
       max(case when tagid = 2 then value end) as velocity, t_stamp as time 
from table t
group by t_stamp;

答案 1 :(得分:0)

SELECT MAX( CASE WHEN tagid = 1
                 THEN value
             END
           ) AS position,
       MAX( CASE WHEN tagid = 2
            THEN value
             END
           ) AS velocity,     
       t_stamp AS time
  FROM YourTable
GROUP BY t_stamp;