将值平均分配到每月的每一天

时间:2021-03-15 10:31:08

标签: sql amazon-redshift

DB-Fiddle

clojure.test

预期结果:

CREATE TABLE PaL (
     id SERIAL PRIMARY KEY,
    event_date DATE,
    marketing_costs DECIMAL
);

INSERT INTO PaL
(event_date, marketing_costs)
VALUES 
('2020-01-01', '500'),
('2020-01-08', '900'),
('2020-01-20', '700'),
('2020-02-15', '600'),
('2020-02-23', '500'),
('2020-03-04', '300'),
('2020-03-19', '800'),
('2020-03-31', '100');


CREATE TABLE dates (
    id SERIAL PRIMARY KEY,
    date DATE
);

INSERT INTO dates
(date)
VALUES 
('2020-01-01'),
('2020-01-02'),
('2020-01-03'),
('2020-01-04'),
('2020-01-05'),
('2020-01-06'),
('2020-01-07'),
('2020-12-31');

在上表中,我在不同的 event_date | marketing_costs | ----------------|-------------------------------|---- 2020-01-01 | 67.74 (=2100/31) | 2020-01-02 | 67.74 (=2100/31) | 2020-01-03 | 67.74 (=2100/31) | 2020-01-04 | 67.74 (=2100/31) | : | : | : | : | : | : | 2020-03-29 | 35.48 (=1100/31) | 2020-03-30 | 35.48 (=1100/31) | 2020-03-31 | 35.48 (=1100/31) | 上有 marketing_costs
在预期的结果中,我想将 event_dates 等于每月的每一天

由于在 marketing_costs 中,我无法在查询中创建每月日期,因此我还有一个名为 redshift 的支持表,其中包含一年中的每个日期。

到目前为止,我能够获得每月总计 dates,但我不知道如何修改查询以将它们平均分配到每一天。

marketing_costs

你有什么想法吗?

1 个答案:

答案 0 :(得分:0)

嗯。 . .如果您的数据中有完整的月份,那么您可以使用窗口函数:

    select 
   d.date, 
   p.marketing_costs,
           p.marketing_costs / count(*) over (partition by date_trunc('month', d.date) as allocated_costs
    from dates d left join
         pal p 
         on d.date = p,event_date;

Modified answer by OP: 使用上述解决方案,我可以使其与此查询一起使用:

SELECT 
d.date AS date_list,
t1.marketing_costs,
(SUM(t1.marketing_costs) OVER (PARTITION BY DATE_TRUNC('month', d.date))) / DATE_PART('day', DATEADD(day, -1, DATEADD(month, +1, DATE_TRUNC('month', d.date)))::date) AS marketing_costs_per_day
FROM dates d
LEFT JOIN

      (SELECT 
      pl.event_date AS event_date,
      SUM(pl.marketing_costs) AS marketing_costs
      FROM PaL pl
      GROUP BY 1) t1 ON t1.event_date = d.date

GROUP BY 1,2
ORDER BY 1;