【问题标题】:How to limit amount of rows for each value?如何限制每个值的行数?
【发布时间】:2020-08-11 11:06:36
【问题描述】:

这是我的示例数据。


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

【问题讨论】:

  • 也指定预期结果。
  • 我已经更新了。

标签: sql postgresql join limit


【解决方案1】:

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

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 是一个 dbfiddle。

【讨论】:

  • 太完美了,非常感谢。不知道行之间和后面是一回事。那将需要我很长时间才能解决。欣赏它。
  • @undecided000 。 . .感谢您提出一个有趣的问题,并且问得很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2014-01-13
  • 2011-04-17
  • 2017-08-28
  • 2021-11-29
相关资源
最近更新 更多