TSQL-2008 SUM(X) OVER (PARTITION … ORDER BY CLAUSE)

后端 未结 2 1042
挽巷
挽巷 2021-01-27 04:52

I really need to take what I have as a result of a CTE, and calculate the cummulative value of groups of data.

The dataset is:

PERIOD  FT  GROUP   DEPT           


        
2条回答
  •  抹茶落季
    2021-01-27 05:41

    This should work. (I changed a forbidden column name from "GROUP" to "GROUP_")

    with cte (PERIOD,  FT,  GROUP_,   DEPT,   VALUE, AccValue) as (select t1.PERIOD,  t1.FT,  t1.GROUP_,   t1.DEPT,    t1.VALUE, SUM(t2.VALUE)   as AccValue
                                from            myTable t1
                                join myTable t2 on t1.PERIOD>= t2.PERIOD
                                and  t1.FT =  t2.FT 
                                and t1.GROUP_ = t2.GROUP_           
                                and t1.DEPT = t2.DEPT
                                group by    t1.PERIOD,  t1.FT,  t1.GROUP_,   t1.DEPT,    t1.VALUE
                        )
                                    select  PERIOD
                        ,FT
                        ,GROUP_
                        ,DEPT
                        ,VALUE
                        ,CASE
                            WHEN FT = 'Actual' THEN AccValue
                            ELSE VALUE
                            END AS AccValue 
                            from cte
                                    order by GROUP_ desc,  FT, PERIOD, DEPT desc,    VALUE
    

提交回复
热议问题