如何限制每个值的行数?

How to limit amount of rows for each value?

这是我的示例数据。


Date         Name    Subject         Importance    Location     Time      Rating
12/08/2020   David   Work            1             London       -         -
1/08/2020    David   Work            3             London       23.50     4
2/10/2018    David   Emails          3             New York     18.20     3
12/08/2020   George  Updates         2             New York     -         -
1/08/2019    George  New Appointments5             London       55.10     2
2/10/2019    David   Emails          3             Paris        18.58     3
8/09/2017    David   Emails          2             Paris        18.90     5

我需要能够看到明天的会议以及我之前与每个客户举行的 3 次会议。因此将按名称排序,然后按日期排序,每个名称的条目限制为 3。有人可以指出正确的方向以便能够做到这一点吗?

预期结果是

Date         Name    Subject         Importance    Location     Time      Rating
12/08/2020   David   Work            1             London       -         -
1/08/2020    David   Work            3             London       23.50     4
2/10/2018    David   Emails          3             New York     18.20     3
2/10/2019    David   Emails          3             Paris        18.58     - 
12/08/2020   George  Updates         2             New York     -         -
1/08/2019    George  New Appointments5             London       55.10     2

您可以使用window函数来计算“明天”的后三个会议的次数。然后进行一些过滤:

select t.*
from (select t.*,
             count(*) filter (where date = current_date + interval '1 day') over
                 (partition by name
                  order by date
                  rows between 1 following and 3 following
                 ) as cnt_tomorrow
      from t
     ) t
where date = current_date + interval '1 day' or
      cnt_tomorrow > 0
order by name, date;

Here 是一个 db<>fiddle.