使用最大日期和间隔汇总前一天的值

时间:2019-11-05 13:53:58

标签: sql postgresql

我试图在一个case语句中使用Max(date)汇总当天的数字,并使用-interval汇总前一天的数字。

select  product
      , sum(
            case
            when date_started = max(date_started)
            then volume
            end )
      as "Current day's Volume"
      , sum(
            case
            when date_started = max(date_started)
            then revenue
            end )
      as "Current day's Revenue"
      , sum(
            case
            when date_started = (max(date_started) - interval '1 day' 
            then volume 
             end ) as "previous day's Volume"
      , sum(
            case
            when date_started = (max(date_started) - interval '1 day' 
            then revenue 
             end ) as "Previous day's Revenue"
  from  lifetime_data
 group by 1

这是在PostgreSQL上。它不起作用。

示例数据 sample

预期结果 results

1 个答案:

答案 0 :(得分:0)

我认为您可以使用子查询和窗口函数来完成所需的工作:

select product,
       sum(volume) filter (where date_started = max_date_started) as current_day_volume,
       sum(revenue) filter (where date_started = max_date_started) as current_day_revenue,
       sum(volume) filter (where date_started = max_date_started - interval '1 day') as previous_day_volume,
       sum(revenue) filter (where date_started = max_date_started - interval '1 day') as previous_day_revenue
from (select ld.*,
             max(date_started) over (partition by product) as max_date_started
      from lifetime_data ld
     ) ld
group by product;