SQlite从表中为每个项目选择前N行

时间:2018-10-19 14:39:11

标签: sql sqlite

我有一个如下表,我试图通过createdDate选择每个流的前2行。

    ID  Name    createdDate(string)
76  Stream1 2018-10-19T00:00:00
76  Stream1 2018-10-18T00:00:00 
76  Stream1 2018-10-17T00:00:00  
70  Stream2 2018-10-17T00:00:00 
70  Stream2 2018-10-03T00:00:00 
70  Stream2 2018-09-22T00:00:00 
21  Stream3 2018-09-21T00:00:00
21  Stream3 2018-09-20T00:00:00 
21  Stream3 2018-08-21T00:00:00 

,输出如下所示,我如何为此查询构建一个

76  Stream1 2018-10-19T00:00:00
76  Stream1 2018-10-18T00:00:00 
70  Stream2 2018-10-17T00:00:00 
70  Stream2 2018-10-03T00:00:00 
21  Stream3 2018-09-21T00:00:00
21  Stream3 2018-09-20T00:00:00 

2 个答案:

答案 0 :(得分:1)

从SQLite 3.25开始,您可以使用ROW_NUMBER

WITH cte AS (
  SELECT *,
    ROW_NUMBER() OVER(PARTITION BY Name
                      ORDER BY CAST(createdDate AS DATE) DESC) AS rn
  FROM tab
)
SELECT *
FROM cte
WHERE rn <= 2;

答案 1 :(得分:0)

您可以使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by id order by cast(createdDate as date) desc) as seq
      from table t
     ) t
where seq <= 2;