SELECT t.id,
c.day,
AVG( COALESCE( t.sales, 0 ) ) OVER (
PARTITION BY id
ORDER BY event_date DESC
RANGE BETWEEN 0 FOLLOWING AND 6 FOLLOWING
) AS avg_last_7_days,
COALESCE(
AVG( COALESCE( t.sales, 0 ) ) OVER (
PARTITION BY id
ORDER BY event_date DESC
RANGE BETWEEN 7 FOLLOWING AND 13 FOLLOWING
),
0
) AS avg_last_8_to_14_days
FROM ( SELECT min_dt + LEVEL - 1 AS day
FROM (
SELECT MIN( event_date ) AS min_dt,
MAX( event_date ) AS max_dt
FROM table_name
)
CONNECT BY LEVEL <= max_dt - min_dt + 1
) c
LEFT OUTER JOIN table_name t
PARTITION BY ( t.id )
ON ( c.day = t.event_date )
ORDER BY id, day DESC
对于样本数据:
CREATE TABLE table_name ( id, sales, event_date ) AS
SELECT 'ABC', 2, DATE '2020-10-16' FROM DUAL UNION ALL
SELECT 'ABC', 5, DATE '2020-10-15' FROM DUAL UNION ALL
SELECT 'ABC', 5, DATE '2020-10-12' FROM DUAL UNION ALL
SELECT 'ABC', 1, DATE '2020-10-11' FROM DUAL UNION ALL
SELECT 'ABC', 3, DATE '2020-10-10' FROM DUAL UNION ALL
SELECT 'ABC', 3, DATE '2020-10-09' FROM DUAL UNION ALL
SELECT 'ABC', 1, DATE '2020-10-08' FROM DUAL UNION ALL
SELECT 'ABC', 4, DATE '2020-10-07' FROM DUAL UNION ALL
SELECT 'ABC', 5, DATE '2020-10-06' FROM DUAL UNION ALL
SELECT 'ABC', 2, DATE '2020-10-04' FROM DUAL UNION ALL
SELECT 'ABC', 3, DATE '2020-10-03' FROM DUAL UNION ALL
SELECT 'ABC', 2, DATE '2020-10-02' FROM DUAL UNION ALL
SELECT 'ABC', 5, DATE '2020-10-01' FROM DUAL UNION ALL
SELECT 'ABC', 4, DATE '2020-09-30' FROM DUAL UNION ALL
SELECT 'ABC', 3, DATE '2020-09-29' FROM DUAL UNION ALL
SELECT 'ABC', 2, DATE '2020-09-28' FROM DUAL UNION ALL
SELECT 'ABC', 1, DATE '2020-09-27' FROM DUAL UNION ALL
SELECT 'ABC', 3, DATE '2020-09-26' FROM DUAL;
1条答案
按热度按时间q1qsirdb1#
在oracle中,您可以使用:
对于样本数据:
输出:
db<>在这里摆弄