How to group by two data fields in a common table expression

I need to compare the final balances of two tables from different clients, grouped by ID. Tables have the same identifier. But one has a few credentials, while the other does not. I need to sum a row from a table with several records, so I only have one end number for calculations.

I have a query that does this a lot, but now I need to get it for a group by month. My current query summarizes it for all dates. In fact, the data should be sorted by identifier and by month so that they know the final monthly balance for each identifier. Is there any way to do this with what I still have?

Thanks in advance.

This is what I still have.

    -- Data setup
    CREATE TABLE [Table1]
    (
        [ID] INT,
        [cost] INT,
        [traceNumber] INT,
        [TheDate] DATE
    )

    INSERT [Table1]
    VALUES  (1, 200, 1001, '9/07/2011'),
            (1, -20, 1002, '9/08/2011'),
            (1, 130, 1003, '10/10/2011'),
            (2, 300, 1005, '10/10/2011')

    CREATE TABLE [Table2]
    (
        [ID] INT,
        [cost] INT
     )

     INSERT [Table2]
    VALUES  (1, 200),
            (2, 300)

    -- Query
    ;WITH [cteTable1Sum] AS
    (
        SELECT [ID], SUM([cost]) AS [cost]
        FROM [Table1]
        GROUP BY [ID]
    )       
    SELECT  [Table1].[ID], 
            [Table1].[TheDate], 
            [Table1].[traceNumber],
            [Table1].[cost] AS [Frost_Balance],
            cte.[cost] AS [SUM_Frost_Balance],
            [Table2].[cost] AS [Ternean_Balance],
            cte.[cost] - [Table2].[cost] AS [Ending_Balance]
    FROM [Table1]
    INNER JOIN [Table2]
        ON [Table1].[ID] = [Table2].[ID]
    INNER JOIN [cteTable1Sum] cte
         ON [Table1].[ID] = cte.[ID]

, .

    WITH [cteTable1Sum] AS 
         ( SELECT [ID], SUM([cost]) 
         AS [cost] FROM [Table1] 
         GROUP BY [ID], [TheDate] )
+5
1

MONTH() YEAR() :

;WITH [cteTable1Sum] AS
    (
        SELECT [ID],
              MONTH(TheDate)  as Mo,
              YEAR(TheDate) as yr,
              SUM([cost]) AS [cost]
        FROM [Table1]
        GROUP BY [ID], MONTH(TheDate), YEAR(TheDate)
    )       

. JOIN :

INNER JOIN [cteTable1Sum] cte
         ON [Table1].[ID] = cte.[ID]
         AND MONTH(Table1.TheDate) = cte.Mo
         AND YEAR(Table1.TheDate) = cte.Yr
+4

All Articles