MySql Select语句应返回唯一行

时间:2011-10-05 14:12:19

标签: mysql

我在 table1 中有以下列名称排名 created_date

我想

SELECT 
    name,
    rank for latest created_date,
    latest created_date, 
    difference between rank current created_date & previous date
FROM
    table1

每个created_date每人只有一条记录。

输出应为:

Sam 15 2011/10/05 -3

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

SELECT
  name,
  rank,
  created_date,
  rank - (
    SELECT rank FROM table1 AS bar
    WHERE bar.created_date < foo.created_date
    ORDER BY created_date DESC
    LIMIT 1
  ) AS diff 
FROM table1 AS foo
ORDER BY created_date DESC
LIMIT 1

编辑:重新阅读您的问题,我想您希望每人获得一个输出行,并计算该人的最后两个记录之间的差异。如果是这样,需要一个稍微复杂的解决方案:

SELECT
  name,
  rank,
  created_date,
  rank - (
    SELECT rank FROM table1 AS bar
    WHERE bar.name = foo.name AND bar.created_date < foo.created_date
    ORDER BY created_date DESC LIMIT 1
  ) AS diff 
FROM table1 AS foo
NATURAL JOIN (
  SELECT name, MAX(created_date) AS created_date FROM table1
  GROUP BY name
) AS blah