简体   繁体   中英

MySql Select Statement that should return a unique row

I have the following columns name , rank , created_date in table1 .

I would like to

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

There is only one record per person per created_date.

Output should be:

Sam 15 2011/10/05 -3

Thanks for your help.

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

Edit: Re-reading your question, I think you want to get one output row per person , with the difference computed between the last two records for that person. If so, a slightly more complicated solution is needed:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM