美文网首页
计算前7天,前30天数据总和

计算前7天,前30天数据总和

作者: 黑曼巴yk | 来源:发表于2020-01-11 23:29 被阅读0次

    前言

    我们开发时候有这样的需求。需要计算前7天,前30天营收总和。以及昨天数据,周数据环比增长等

    实现

    如果使用 left join来做会非常麻烦,甚至出错。比如1天的数据left join 7天前的数据之后输出的是7天数据再left join 14天数据则变成 7 * 14的输出。数据会膨胀非常多

    这里提供一条思路:使用开窗函数 over(order by rows between xx and xx)来解决

    SELECT  theday
                        userid
                        ,gaap_day
                        ,yunyan_secd_prd_name
                        ,productid
                        ,sum(gaap_day) OVER (PARTITION BY userid, yunyan_secd_prd_name, productid ORDER BY theday ROWS BETWEEN 1 PRECEDING AND CURRENT ROW ) AS gaap_1day_sum
                        ,sum(gaap_day) OVER (PARTITION BY userid, yunyan_secd_prd_name, productid ORDER BY theday ROWS BETWEEN 7 PRECEDING AND CURRENT ROW ) AS gaap_7day_sum
                        ,sum(gaap_day) OVER (PARTITION BY userid, yunyan_secd_prd_name, productid ORDER BY theday ROWS BETWEEN 14 PRECEDING AND CURRENT ROW ) AS gaap_14day_sum
                        ,sum(gaap_day) OVER (PARTITION BY userid, yunyan_secd_prd_name, productid ORDER BY theday ROWS BETWEEN 30 PRECEDING AND CURRENT ROW ) AS gaap_30day_sum
                FROM    demo_bi.crm_gaap_day_cid_uid
                WHERE   theday >= to_char(dateadd(to_date('${bizdate}', 'yyyymmdd'), - 30, 'dd'), 'yyyymmdd')
                AND     theday <= '${bizdate}'
    

    相关文章

      网友评论

          本文标题:计算前7天,前30天数据总和

          本文链接:https://www.haomeiwen.com/subject/lazbactx.html