Get the average traffic from last week data per WEEK number and get the traffic data for last week Traffic(D-7)
For example if date = 5/13/2023, need to output traffic data (Traffic(D-7)) for date = 5/6/2023
I manage to get the Average but no idea how to retrieve the date-7 data and output it altogether
create table a
(
date varchar(50),
Tname varchar(50),
Week varchar(5),
Traffic float
)
insert into a values ('5/1/2023', 'ID1', '18', 7.98)
insert into a values ('5/2/2023', 'ID1', '18', 4.44)
insert into a values ('5/3/2023', 'ID1', '18', 5.66)
insert into a values ('5/4/2023', 'ID1', '18', 10.01)
insert into a values ('5/5/2023', 'ID1', '18', 9.41)
insert into a values ('5/6/2023', 'ID1', '18', 6.71)
insert into a values ('5/7/2023', 'ID1', '18', 8.24)
insert into a values ('5/8/2023', 'ID1', '19', 8.97)
insert into a values ('5/9/2023', 'ID1', '19', 6.74)
insert into a values ('5/10/2023', 'ID1', '19', 6.45)
insert into a values ('5/11/2023', 'ID1', '19', 9.33)
insert into a values ('5/12/2023', 'ID1', '19', 8.08)
insert into a values ('5/13/2023', 'ID1', '19', 8.36)
SELECT date, Tname, Week,
AVG(Traffic) OVER(PARTITION BY Week) AS AVTraffic
FROM a
ORDER BY week
3
Answers
First of all, you need to fix your flaws in your table schema design, and declare:
VARCHAR(50)
)INT
type (instead ofVARCHAR(5)
)DECIMAL
type (instead ofFLOAT
)Once you’ve carried it out, you can solve this problem by:
ROW_NUMBER
LAG
, by partitioning on your ranking created at previous step, and ordering on the week_number.And if you realize that you may have holes among your weeks (…, week 17, week 18, week 20, week 21, …) and specifically want values from the exact previous week (that may be missing), you can add a filter on the
LAG
function, that checks if week and previous week are consecutive:(in place of
LAG(Traffic) OVER(...)
only)Output:
Check the demo here.
Note (1): The last
ORDER BY
clause is not needed. It’s there just for visualization purposes.Note (2): This solution assumes you have 7 evaluations per week, each made in a separate day.
Use the window function
LAG
with a7 PRECEDING
frame to catch the values from 7 days ago, so that you can avoid using unnecessary subqueries or even self joins, e.g.Note:
date
. I had to cast it to make the query work properly.Demo:
db<>fiddle
Try a left self-join as the following:
demo