【问题标题】:Divide value equally to each day of the month将值平均分配给每月的每一天
【发布时间】:2021-03-15 10:31:08
【问题描述】:

DB-Fiddle

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 的总数,但我不知道如何修改查询以将它们平均分配到每一天。

SELECT
DATE_TRUNC('month', pl.event_date)::date AS month,
SUM(pl.marketing_costs)
FROM PaL pl
GROUP BY 1;

你有什么想法吗?

【问题讨论】:

    标签: sql amazon-redshift


    【解决方案1】:

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

        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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      相关资源
      最近更新 更多