1

我有一个形式的 MySQL 表...

record    timestamp
1         2014-07-10
2         2014-07-10
1         2014-07-11
2         2014-07-11
1         2014-07-12
2         2014-07-12

...并且我想以返回一组表单的方式查询它...

record    1st time    2nd time    3rd time
1         2014-07-10  2014-07-11  2014-07-12
2         2014-07-10  2014-07-11  2014-07-12
...

我很乐意使用MAX()和子查询来实现最近的时间戳,但这似乎更适合返回可迭代的 SQL 对象。例如,如果我可以用类似的东西创建上述内容......

SELECT record, timestamp[0] AS "1st time", timestamp[1] AS "2nd time", timestamp[2] AS "3rd time"

...那很好啊。这个东西PIVOT()可以用吗?

4

1 回答 1

0

对于上述限制为 3 列的数据集,您可以执行以下操作

SELECT t1.record,
MAX(CASE WHEN t1.rownum = 1 THEN t1.timestamp  END) AS `1st time`,
MAX(CASE WHEN t1.rownum = 2 THEN t1.timestamp  END) AS `2nd time`,
MAX(CASE WHEN t1.rownum = 3 THEN t1.timestamp  END) AS `3rd time`
FROM (
  SELECT t.*,
  @r:= CASE WHEN @g= record THEN @r + 1 ELSE 1 END rownum,
  @g:=record
  FROM table t
  CROSS JOIN (SELECT @g:=0,@r:=0) t1
  ORDER BY `record`, `timestamp`
  ) t1
GROUP BY t1.record

Demo

于 2014-08-28T21:38:41.183 回答