Trailing Sum Query

后端 未结 2 508
刺人心
刺人心 2020-12-21 14:27

I am looking to summarize date and need to find a way of doing a 3 day trailing sum, sum of the current date and the 2 previous days. I am using MariaDB, a MYSQL fork.

2条回答
  •  梦毁少年i
    2020-12-21 14:53

    A fast way using MySQL variables

    Sample table:

    create table keywordsum (date datetime, total int);
    insert keywordsum values
    ('2010-11-11',316815),
    ('2010-11-12',735305),
    ('2010-11-13',705116),
    ('2010-11-14',725020),
    ('2010-11-15',745378);
    

    Query:

    select
      k.date, k.total, k.total + ifnull(@d1,0) + ifnull(@d2,0) running_total,
      @d2 := @d1,
      @d1 := k.total
    from (select @d1 := null, @d2 := null) vars
    cross join keywordsum k
    order by k.date
    

    (You can always subselect this to get only the first 3 columns)

提交回复
热议问题