Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Returning Cumulative Monthly Column Values

I have this SQL query that I use to find Trial Balance movements per account per month.

/* Fixed Assets 1 */
SELECT * FROM
(
    SELECT T0.AcctCode AS 'SAP Code', T0.AcctName AS 'Description', 
    MONTH(T1.RefDate) AS Month, SUM(T1.Debit - T1.Credit) AS 'Amount'
    FROM OACT T0
    LEFT JOIN JDT1 T1 ON T0.[AcctCode] = T1.[Account] 
    WHERE T0.AcctCode LIKE '111%' AND T0.Levels = 5
    AND (T1.RefDate BETWEEN DATEADD(yy, DATEDIFF(yy,0,{?AsAtDate}), 0) AND {?AsAtDate}) 
    GROUP BY T0.AcctCode, T0.AcctName, T0.FatherNum, T1.RefDate) AS q
    PIVOT
(
SUM(Amount) 
FOR [Month] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) AS query

This returns the following results from June :

enter image description here

I would like to include cumulative monthly results for all rows such that row 1 results should be:

1, 111110, Building Gross Value, 633604.23, 637764.23, 645313.03, 649061.78, 651097.78, 651097.78, 651397.78

I have not been successful in achieving this. How do I modify the query to achieve this?

Additional data:

The query:

SELECT CAST(T0.TaxDate AS Date), T0.Account, T1.AcctName, T0.Debit, T0.Credit
FROM JDT1 T0 INNER JOIN OACT T1
ON T0.Account = T1.AcctCode
WHERE T0.[Account] = '111110'

Returns:

enter image description here

like image 650
Kinyanjui Kamau Avatar asked Oct 19 '22 13:10

Kinyanjui Kamau


1 Answers

You need outer select in which you add your columns to another:

SELECT AcctCode AS 'SAP Code', AcctName AS 'Description', 
col1 AS '1', 
col1 + col2 AS '2', 
col1 + col2 + col3 AS '3',
... FROM (
    SELECT AcctCode, AcctName, 
    [1] AS col1, 
    [2] AS col2, 
    [3] AS col3,
    ... FROM
    (
        SELECT T0.AcctCode, T0.AcctName, 
        MONTH(T1.RefDate) AS Month, SUM(T1.Debit - T1.Credit) AS 'Amount'
        FROM OACT T0
        LEFT JOIN JDT1 T1 ON T0.[AcctCode] = T1.[Account] 
        WHERE T0.AcctCode LIKE '111%' AND T0.Levels = 5
        AND (T1.RefDate BETWEEN DATEADD(yy, DATEDIFF(yy,0,{?AsAtDate}), 0) AND {?AsAtDate}) 
        GROUP BY T0.AcctCode, T0.AcctName, T0.FatherNum, T1.RefDate) AS q
        PIVOT
    (
    SUM(Amount) 
   FOR [Month] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
    ) AS query
)
like image 84
dey Avatar answered Oct 21 '22 21:10

dey