1

I have a table that has the following columns:

  • Event Date
  • Location
  • Employee Id
  • Task Name
  • Volume Per Hour

Using PostgreSQL, I need to calculate the 75th percentile of Volume Per Hour for a given location and task name across all employee ids and event dates assuming a rolling 7 day window. For example, if the event date is 11/16/2020, I would take the 75th percentile of volume per hour for all the individual dates and employee ids between 11/09/2020 and 11/16/2020. Can someone help me with this problem?

Sample Data:

Sample Data

Sample Output:

Sample Output

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
ss1891
  • 11
  • 2
  • You tagged amazon redshift, but mentioned postgres in your question. – Philipp Johannis Nov 17 '20 at 20:44
  • Welcome here @user14652614 . In order to help us to support you, please provide a more simple explanation about what you need to do as we may do not understand your domain terms. If you provide some formulas for your calculation will be helpful. – Useme Alehosaini Nov 17 '20 at 21:46

1 Answers1

1

You should be able to achieve this by using generate_series and percentile_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;
Philipp Johannis
  • 2,718
  • 1
  • 15
  • 18
  • Your approach of joining between event_date-7 and event_date worked great in getting a trailing 7 day window at a daily level. This worked perfectly, thank you! – ss1891 Nov 18 '20 at 03:16
  • 1
    Great to hear, could you mark this as answer then, and welcome to the community – Philipp Johannis Nov 18 '20 at 07:51