Sqlite:如何从结果集中获取每日前N个结果

时间:2016-12-10 14:39:08

标签: sql sqlite

我有这样的查询:

SELECT TradeDate, Ticker, SUM(Net_Sold) AS Net_Sold FROM report 
WHERE Issuer='ABC' AND TradeDate>='20161205'
GROUP BY ticker, TradeDate ORDER BY TradeDate, Net_Sold ASC

返回以下输出结果集:

 TradeDate   Ticker      Net_Sold
 20161205   388 HK -3174437.4380
 20161205   941 HK -3113297.9650
 20161205   358 HK -2373509.1600
 20161205  2318 HK -1456734.7500
 20161206   175 HK -1074980.3250
 20161206  1928 HK  -882339.0880
 20161206  2388 HK  -489695.4150
 20161206   941 HK  -383618.2200
 20161207  1211 HK  -341908.9750
 20161207  1766 HK  -263330.6400
 20161207   2318 HK  -226313.7380
 20161207   388 HK  -206908.1000

我的问题是如何编写一个sqlite查询,每天都会返回我的前2位数据?我期待这样的输出:

20161205   388 HK -3174437.4380
20161205   941 HK -3113297.9650
20161206   175 HK -1074980.3250
20161206  1928 HK  -882339.0880
20161207  1211 HK  -341908.9750
20161207  1766 HK  -263330.6400

1 个答案:

答案 0 :(得分:1)

SQLite支持row_number()或变量。这使子查询成为处理这个问题的一种方法:

WITH t AS (
      SELECT TradeDate, Ticker, SUM(Net_Sold) AS Net_Sold
      FROM report 
      WHERE Issuer = 'ABC' AND TradeDate >= '20161205'
      GROUP BY ticker, TradeDate
      ORDER BY TradeDate, Net_Sold ASC
     )
SELECT t.*
FROM t
WHERE (SELECT COUNT(*)
       FROM t t2
       WHERE t2.TradeDate = t.TradeDate AND
             t2.Net_Sold >= t.NetSold
      ) <= 2;

或者,或者:

WITH t AS (
      SELECT TradeDate, Ticker, SUM(Net_Sold) AS Net_Sold
      FROM report 
      WHERE Issuer = 'ABC' AND TradeDate >= '20161205'
      GROUP BY ticker, TradeDate
      ORDER BY TradeDate, Net_Sold ASC
     )
SELECT t.*
FROM t
WHERE t.ticker IN (SELECT t2.ticker
                   FROM t t2
                   WHERE t2.TradeDate = t.TradeDate
                   ORDER BY t2.NetSold DESC
                   LIMIT 2
                  );