2

If I have a date column, example "2013-05-05", how do I select the previous record? I tried

SELECT DATE, percent_change
FROM aa
WHERE DATE >2012 -12 -31
ORDER BY DATE DESC 
LIMIT 1
2
  • do you want to select the previous record after ordering the record by date? Commented Jun 9, 2013 at 4:05
  • Er, "2013-05-05" is not "2012-12-31" !?!?! Commented Jun 9, 2013 at 7:55

2 Answers 2

1

Assuming that date is a unique key:

SELECT `date`, percentage_change FROM aa WHERE `date`>'2012-12-31' ORDER BY `date` DESC LIMIT 1;

Then, to get the previous record:

SELECT `date`, percentage_change FROM aa WHERE `date`>'2012-12-31' ORDER BY `date` DESC LIMIT 1 OFFSET 1;

And the record before that:

SELECT `date`, percentage_change FROM aa WHERE `date`>'2012-12-31' ORDER BY `date` DESC LIMIT 1 OFFSET 2;

etc.

Sign up to request clarification or add additional context in comments.

2 Comments

This returns the most recent entry, 2013-06-05.
Oh, I see what you're asking. I believe you are looking for the OFFSET syntax. See edits above.
0

To get the record before a given date, this should work:

SELECT DATE, percent_change 
FROM aa 
WHERE DATE < '2013-05-05' 
ORDER BY DATE DESC
LIMIT 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.