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
Simple INNER JOIN should do the trick. Unless I'm misunderstanding you, what you want is a running total, correct?
This example creates a dummy table with dummy data, then uses an inner join for the running total. From a performance standpoint, the Common Table Expression is likely more efficient. But for simplicity, the inner join my be preferential.
/* Dummy table */
create table testing1
(col1 int not null identity(1,1),
col2 varchar(5),
col3 int)
insert into testing1
values ('a', 10), ('a', 20), ('a', 30), ('b', 40), ('b', 50)
/* Running total example */
SELECT a.col1
, a.col2
, a.col3
, SUM(b.col3) AS total
FROM testing1 a INNER JOIN testing1 b
ON a.col1 >= b.col1
AND a.col2 = b.col2
GROUP BY a.col1, a.col2, a.col3
ORDER BY a.col1
/* Edit to include Output */
col1 col2 col3 total
1 a 10 10
2 a 20 30
3 a 30 60
4 b 40 40
5 b 50 90
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