SQL:从返回集创建序数列

时间:2014-08-28 21:23:40

标签: mysql ordinal

我有一个表格的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()可以用于什么?

1 个答案:

答案 0 :(得分: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