限制在 SQLite3 SELECT 查询中选择的唯一日期数

Limiting number of unique dates selected in SQLite3 SELECT Query

基本上,这是我拥有的 SQLite3 table: Click Here for Image

如图所示,有 8 个不同的日期,从 29/07/2021 到 05/08/2021。我想 运行 一个 SQLite3 查询 returns 只有这 8 个日期中的最新 7 个(即 30/07/2021 到 05/08/2021)但是它 returns 所有行每个日期。

我试过像这样使用 LIMIT 关键字:

all_app_data = sorted(conn.execute('SELECT date, application, usage_time FROM monitor '
                                   'ORDER BY date DESC, usage_time ASC LIMIT 7').fetchall()) 

但是,这只会从每个日期中提取 1 行(即 2021 年 7 月 30 日的 1 行,而不是当前的 5 行)。我该如何解决这个问题?

您可以通过在子查询中收集符合条件的日期来做到这一点:

SELECT m1.date, m1.application, m1.usage_time 
FROM monitor m1 
WHERE m1.date IN
  (SELECT DISTINCT m2.date 
   FROM monitor m2
   ORDER BY m2.date DESC LIMIT 7)
ORDER BY m1.date DESC, m1.usage_time ASC

(您也可以针对子查询加入)

您可以使用 DENSE_RANK() window 函数来实现:

SELECT date, application, usage_time 
FROM (
  SELECT *, DENSE_RANK() OVER (ORDER BY date DESC) rn
  FROM monitor
) 
WHERE rn <= 7
ORDER BY date DESC, usage_time ASC