MySQL从另一行中选择一行值

时间:2013-10-27 18:08:14

标签: mysql sql

我有一个超简单查询SELECT TIME, VALUE, TYPE from mylog;

我的查询显示下一个:

| TIME            | VALUE |      TYPE |
 -------------------------------------
| 2013-09-26 04:45|  18.7 |         1 |
| 2013-09-26 04:45|  84.5 |         2 |
| 2013-09-26 05:00|  18.6 |         1 |
| 2013-09-26 05:00|  84.7 |         2 |

但我希望查询显示下一个:

| TIME            | VALUE A |  VALUE B  |  
 ----------------------------------------
| 2013-09-26 04:45|  18.7   |  85.5     |  
| 2013-09-26 05:00|  18.6   |  84.7     |  

其中VALUE AType = 1VALUE BType = 2

所有数据都存储在一个表中,并包含以下列:

TIME, VALUE, TYPE

2 个答案:

答案 0 :(得分:1)

SELECT TIME,
MIN(CASE WHEN TYPE= '1' THEN VALUE ELSE NULL END)   AS VALUE_A,
MIN(CASE WHEN TYPE= '2' THEN VALUE ELSE NULL END)   AS VALUE_B From mylog GROUP BY time

SQL fiddle

答案 1 :(得分:1)

SELECT
  `TIME`,
  MIN(IF(`TYPE`=1,`VALUE`,99999999)) AS `Value A`,
  MIN(IF(`TYPE`=2,`VALUE`,99999999)) AS `Value B`
FROM mylog
GROUP BY `TIME`

99999999提出“没有价值”

修改

我不使用NULL,因为它会拒绝MIN(或MAX)。如果你想要NULL,你必须在

中包装它
SELECT `TIME`, 
  IF(`Value A`=99999999,NULL,`Value A`),
  IF(`Value B`=99999999,NULL,`Value B`)
FROM (
   -- ...
) AS baseview