mysqldatabasedolphindb

how do I group, sort and take out the first N in mysql?


I can get the sorted data in the group, and finally take out the first N in DolphinDB.

But how do I group, sort and take out the first N in mysql?

Thank you first.

The DolphinDB code is as follows:

sym = `C`MS`MS`MS`IBM`IBM`C`C`C$symbol;
price= 49.6 29.46 29.52 30.02 174.97 175.23 50.76 50.32 51.29;
qty = 2200 1900 2100 3200 6800 5400 1300 2500 8800;
timestamp = [09:34:07,09:36:42,09:36:51,09:36:59,09:32:47,09:35:26,09:34:16,09:34:26,09:38:12];
t1 = table(timestamp, sym, qty, price);
select top 2 * from t1 context by sym csort timestamp;

timestamp sym qty  price 
--------- --- ---- ------
09:34:07  C   2200 49.6  
09:34:16  C   1300 50.76 
09:32:47  IBM 6800 174.97
09:35:26  IBM 5400 175.23
09:36:42  MS  1900 29.46 
09:36:51  MS  2100 29.52


Solution

  • If you have MySQLv8.0 that supports ROW_NUMBER() you can use something like this:

     SELECT `timestamp`,sym,qty,price
      FROM
          (
          SELECT 
          `timestamp`,sym,qty,price,ROW_NUMBER() OVER (PARTITION BY sym ORDER BY timestamp ASC) AS ranking
          FROM `table`
          ) t
    WHERE ranking<3   
    

    https://www.db-fiddle.com/f/8fY2DJmCCv7kCnEAPBAU3B/0