計算截止每個時間點的累計值

-- 計算每個公司每個月的累計值(這種情況下,如果某個公司某個月沒有銷售額,這個公司在這個月的記錄就沒有)
select t.year,
    t.month,
    companyid,
    companyname,
    sum(amount) over(partition by companyid, companyname,year order by t.month) amount
from (
    select t.year,
        t.month,
        companyid,
        companyname,
        sum(amount) amount
    from property_finance_final
    group by t.year, t.month, companyid, companyname

) t


--時間補全的截至每個月月底累計值

select substr(t1.the_month,1,4),substr(t1.the_month,6,2),
    t2.companyid,t2.companyname,sum(t2.amount) amount
from(
    select the_month
    from dim.dim_date
    where the_date<'2018-07-02'
    group by the_month
)t1
left join
(
    select t.year,
        t.month,
        companyid,
        companyname,
        sum(amount) over(partition by companyid, companyname,year order by t.month) amount
    from (
        select t.year,
            t.month,
            companyid,
            companyname,
            sum(amount) amount
        from property_finance_final t
        group by t.year, t.month, companyid, companyname
    ) t
)t2
on(1=1)
where t1.the_month>=concat(t2.year,'-',t2.month)
group by substr(t1.the_month,1,4),substr(t1.the_month,6,2),
    t2.companyid,t2.companyname


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章