简体   繁体   中英

MySQL query to select a row based on values of Nth previous row

My second attempt to ask this question, hopefully the example is simpler and my question is more clear...

I simply want to query for stock symbols whos most recent price is greater than its price N-rows previous (sorted by date, however the dates are not consecutive). For this example we'll set N=5, so compare price to the price 5 rows earlier.

Out put should be the symbol, most recent date, price, price-n-rows-ago, date-n-rows-ago.

Here is a link to the schema/data... http://sqlfiddle.com/#!2/bbb54/2

Output should look like this:

Symbol, Price,      Date, Price5RowAgo, Date5RowsAgo
AA      16.37  2014-11-06        16.22    2014-10-11
ADT     36.07  2014-11-05        35.19    2014-10-23
AEO     13.82  2014-11-03        12.86    2014-10-07

(note, AFA is not in result as it doesn't meet the criteria)

If read many questions/solutions about using values from a previous row but can't quite seem to adapt any of them to this particular situation. Any help and suggestions are much appreciated!

The best way I can think of to do this is to use subqueries to get the previous rows. I tried putting them as a single subquery, but it looks like you can't select multiple columns for a subquery when you're adding it as a select column. Maybe someone can condense the two down to one.

SELECT *, 
  (SELECT p2.`DATE` FROM PRICES as p2 WHERE p2.`SYMBOL`=p1.`SYMBOL` ORDER BY p2.`DATE` LIMIT 5,1) as previousDate,
  (SELECT p2.`PRICE` FROM PRICES as p2 WHERE p2.`SYMBOL`=p1.`SYMBOL` ORDER BY p2.`DATE` LIMIT 5,1) as previousPrice
FROM PRICES as p1 GROUP BY p1.`SYMBOL`;

Obviously, change the LIMIT 5,1 in the subquery as needed to go back the number of rows desired.

Thank you @huykir!! with some minor edits this is now working perfectly. Here is the final version...

SELECT *, 
  (SELECT p2.`DATE` FROM PRICES as p2 WHERE p2.`SYMBOL`=p1.`SYMBOL` ORDER BY p2.`DATE` DESC LIMIT 5,1) as previousDate,
  (SELECT p2.`PRICE` FROM PRICES as p2 WHERE p2.`SYMBOL`=p1.`SYMBOL` ORDER BY p2.`DATE`   DESC LIMIT 5,1) as previousPrice
FROM PRICES as p1 
GROUP BY p1.`SYMBOL`
HAVING PRICE>PREVIOUSPRICE
ORDER BY p1.SYMBOL ASC, p1.DATE DESC

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