如何从数据库中获取上一行值?

时间:2017-07-25 06:53:44

标签: mysql database

假设我有下表,让它成为表“A”。

Select * FROM A;
  ID       Score
  1        25
  2        36
  3        12
  4        14

我想查询按升序选择分数以及prev分数值(存储在新创建的列“prev_score”中),如下所示。

  ID       Score      Prev_Score
  3        12            0
  4        14            12
  1        25            14
  2        36            25

可以使用单个SQL查询来完成吗?

1 个答案:

答案 0 :(得分:2)

您可以使用相关子查询来获取之前的值:

SELECT t1.ID, t1.Score, 
       COALESCE((SELECT Score
                 FROM mytable AS t2
                 WHERE t2.Score < t1.Score
                 ORDER BY t2.Score LIMIT 1), 0) AS Previous
FROM mytable AS t1
ORDER BY t1.Score DESC;

Demo here

修改

如果您希望得分按升序排列,则只需切换ASC / DESC关键字:

SELECT t1.ID, t1.Score, 
       COALESCE((SELECT Score
                 FROM mytable AS t2
                 WHERE t2.Score > t1.Score
                 ORDER BY t2.Score DESC LIMIT 1), 0) AS Previous
FROM mytable AS t1
ORDER BY t1.Score;