【问题标题】:How do I set up a rolling 7 day 75th percentile in SQL?如何在 SQL 中设置滚动的 7 天第 75 个百分位数?
【发布时间】:2020-11-17 06:03:09
【问题描述】:

我有一个包含以下列的表格:

  • 活动日期
  • 位置
  • 员工编号
  • 任务名称
  • 每小时处理量

使用PostgreSQL,我需要计算所有员工 ID 和事件日期中给定位置和任务名称的每小时交易量的第 75 个百分位(假设滚动窗口为 7 天)。例如,如果活动日期是 2020 年 11 月 16 日,我将采用 2020 年 11 月 9 日到 2020 年 11 月 16 日之间的所有个人日期和员工 ID 的每小时交易量的第 75 个百分位。 有人可以帮我解决这个问题吗?

样本数据:

样本输出:

【问题讨论】:

  • 您标记了 amazon redshift,但在您的问题中提到了 postgres。
  • 欢迎来到这里@user14652614。为了帮助我们为您提供支持,请提供更简单的说明来说明您需要做什么,因为我们可能不理解您的域术语。如果您提供一些公式对您的计算会有所帮助。

标签: sql amazon-redshift aggregate-functions window-functions percentile


【解决方案1】:

您应该可以通过使用generate_seriespercentile_disc 来实现此目的

with data_example as
(
 SELECT * FROM (VALUES 
 (date '2020-11-16','ABC',1,'Inbound',10),
 (date '2020-11-16','ABC',2,'Inbound',20),
 (date '2020-11-15','ABC',1,'Inbound',30),
 (date '2020-11-17','ABC',1,'Inbound',10)
 ) AS t (event_date,location,emp_id,task_name,volume)
)
,dates as
(
select generate_series(
           (date '2020-11-10')::timestamp,
           (date '2020-11-25')::timestamp,
           interval '1 day'
         ) as event_date
)
select d.event_date
, d.event_date - INTERVAL '7 day' AS window_start
,location
,task_name
,percentile_disc(0.75) within group (order by de.volume) perc_volume
,count(1) cnt
from dates d
join data_example de
    on de.event_date between d.event_date- INTERVAL '7 day' and d.event_date
group by 1,2,3,4
order by 1,2,3,4;

【讨论】:

  • 您在 event_date-7 和 event_date 之间加入的方法非常适合在每天的水平上获得 7 天的尾随窗口。效果很好,谢谢!
  • 很高兴听到这个消息,您能否将其标记为答案,欢迎加入社区
猜你喜欢
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 2014-03-25
  • 2015-08-01
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 2011-11-01
相关资源
最近更新 更多