Skip to content
Advertisement

Add rows accumulated by current month

Is there a way to translate my hard coded SQL script into a dynamic?

My problem with this code is that, it still adding the SEPT-DEC it should be zero since we are not yet covered this month

  SELECT *,
  [JAN] [JAN TO JAN]  ,  
  [JAN] + [FEB]  [JAN TO FEB] ,
  [JAN] + [FEB] + [MAR] [JAN TO MAR],
  [JAN] + [FEB] + [MAR] + [APR] [JAN TO APR]    ,
  [JAN] + [FEB] + [MAR] + [APR] + [MAY] [JAN TO MAY]    ,
  [JAN] + [FEB] + [MAR] + [APR] + [MAY] + [JUN] [JAN TO JUN]    ,
  [JAN] + [FEB] + [MAR] + [APR] + [MAY] + [JUN] + [JUL] [JAN TO JUL],
  [JAN] + [FEB] + [MAR] + [APR] + [MAY] + [JUN] + [JUL] + [AUG] [JAN TO AUG],
  [JAN] + [FEB] + [MAR] + [APR] + [MAY] + [JUN] + [JUL] + [AUG] + [SEP] [JAN TO SEP],
  [JAN] + [FEB] + [MAR] + [APR] + [MAY] + [JUN] + [JUL] + [AUG] + [SEP] + [OCT]  [JAN TO OCT],
  [JAN] + [FEB] + [MAR] + [APR] + [MAY] + [JUN] + [JUL] + [AUG] + [SEP] + [OCT] + [NOV] [JAN TO NOV],
  [JAN] + [FEB] + [MAR] + [APR] + [MAY] + [JUN] + [JUL] + [AUG] + [SEP] + [OCT] + [NOV] + [DEC] [JAN TO DEC]
  FROM TEST_CHANNEL_YTD

My table

enter image description here

Expected Result:

Starts from JAN then Added the succeeding covered months.

enter image description here

Advertisement

Answer

You can UNPIVOT your data, use the window function sum() over() to calculate the running total and then PIVOT the results.

Example

Select *
 From  (
        Select Year
              ,Channels
              ,Col
              ,Amt
         From TEST_CHANNEL_YTD A
         Cross Apply ( 
                      Select Col
                            ,Amt = sum(Amt) over (Order by Seq)
                       From (values ('Jan to Jan',1,Jan)
                                   ,('Jan to Feb',2,Feb)
                                   ,('Jan to Mar',3,Mar)
                                   ,('Jan to Apr',4,Apr)
                                   ,('Jan to May',5,May)
                                   ,('Jan to Jun',6,Jun)
                                   ,('Jan to Jul',7,Jul)
                                   ,('Jan to Aug',8,Aug)
                                   ,('Jan to Sep',9,Sep)
                                   ,('Jan to Oct',10,Oct)
                                   ,('Jan to Nov',11,Nov)
                                   ,('Jan to Dec',12,Dec)
                               ) V (Col,Seq,Amt)
                        ) B
       ) src 
 Pivot ( sum(Amt) for Col in ([Jan to Jan],[Jan to Feb],[Jan to Mar],[Jan to Apr],[Jan to May],[Jan to Jun],[Jan to Jul],[Jan to Aug],[Jan to Sep],[Jan to Oct],[Jan to Nov],[Jan to Dec]) ) pvt

Results

enter image description here

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement