如何按公共表表达式中的两个数据字段进行分组

时间:2011-10-10 15:17:45

标签: sql sql-server-2008 group-by common-table-expression

我需要比较来自按ID分组的不同客户的两个表的最终余额。这些表具有相同的ID但是一个具有多个ID条目而另一个没有。我需要从表中对具有多个条目的行求和,因此我只有一个最终数字来进行计算。

我有这么多的查询,但现在我需要按月分组。我当前的查询总计所有日期。实际上,数据需要按ID和按月排序,以便他们知道每个ID的结束月度余额。到目前为止,有没有办法做到这一点?

提前致谢。

这是我到目前为止所做的。

    -- 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] )

1 个答案:

答案 0 :(得分:4)

您应该使用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)
    )       

这将为您提供每个ID的每月月度细分。然后将JOIN更改为:

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