-1

I need to get the latest rows ORDERED BY created_at LIMIT 1 for each symbol. So if i want AAPL and GOOGL latest rows, I would return rows 5 and 10 because their created_at is the latest. I khnow it would be something along the lines of
SELECT * FROM stocks WHERE symbol IN ("AAPL","GOOGL") ORDER BY created_at
How can I do this?

stocks
+----+--------+---------------+---------------------------+
| id | symbol | price         |  created_at               |
+----+--------+---------------+---------------------------+
|  1 | AAPL   |        498.20 |2020-08-25 17:40:48.692584 |
|  2 | AAPL   |        498.21 |2020-08-25 17:42:48.743049 |
|  3 | AAPL   |        498.22 |2020-08-25 17:43:48.783471 |
|  4 | AAPL   |        498.23 |2020-08-25 17:44:48.844545 |
|  5 | AAPL   |        498.24 |2020-08-25 17:45:48.868454 |
|  6 | GOOGL  |        100.20 |2020-08-25 17:50:48.901309 |
|  7 | GOOGL  |        100.21 |2020-08-25 17:52:48.935137 |
|  8 | GOOGL  |        100.22 |2020-08-25 17:54:48.957983 |
|  9 | GOOGL  |        100.23 |2020-08-25 17:56:48.973070 |
| 10 | GOOGL  |        100.24 |2020-08-25 17:58:49.002871 |
+----+--------+---------------+---------------------------+



Results:
+----+--------+---------------+---------------------------+
| id | symbol | price         |  created_at               |
+----+--------+---------------+---------------------------+
|  5 | AAPL   |        498.24 |2020-08-25 17:45:48.868454 |
| 10 | GOOGL  |        100.24 |2020-08-25 17:58:49.002871 |
+----+--------+---------------+---------------------------+
user207421
  • 305,947
  • 44
  • 307
  • 483
MalcolmInTheCenter
  • 1,376
  • 6
  • 27
  • 47

2 Answers2

1
SELECT t1.*
FROM stocks t1
NATURAL JOIN ( SELECT symbol, MAX(created_at) created_at
               FROM stocks
               GROUP BY symbol ) subquery
-- WHERE symbol IN ("AAPL","GOOGL") 
-- ORDER BY created_at
Akina
  • 39,301
  • 5
  • 14
  • 25
0

Please try this if it works:

SELECT * FROM stocks WHERE Created IN (SELECT MAX(Created) FROM stocks GROUP BY Symbol);

Here is the working solution for this

Solution to your question

bhuvnesh pattnaik
  • 1,365
  • 7
  • 14