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
精彩评论