如何对分组表T-Sql进行分组

时间:2014-10-03 21:01:35

标签: sql sql-server tsql

我有以下Sql代码:

DECLARE @Temp Table
  (
    Amount int,
    Name nvarchar(50),  
    Year nvarchar(4),
    Month nvarchar(2)
  )
  INSERT INTO @Temp

  SELECT
        count(*),
        t3.Name,
        Year(t1.DateReceived),
        Month(t1.DateReceived)
  FROM
        TableOne t1,
        TableTwo t2, 
        TableThree t3
 WHERE
        t1.ID = t2.t1_ID and
        t2.ID = t3.t2_ID
    GROUP BY
        t3.Name, 
        Year(t1.DateReceived),
        Month(t1.DateReceived)

        SELECT 
        Amount, 
        Name, 
        YearReceived + '-' + RIGHT('00'+MonthReceived,2) as Period FROM @Temp

我得到了这个结果:


Amount   Name         Period
15       Product 1    2014-09
29       Product 2    2014-09
1        Product 3    2014-09

现在,我不知道如何将这些行分成一行,每个时期,即


Product 1 Product 1_Sum  Product 2 Product 2_Sum Product 3 Product 3_Sum  Period
--------------------------------------------------------------------------------
Product 1 15             Product 2 29            Product 3 1              2014-09
.         .              .         .             .         .              .
.         .              .         .             .         .              .
Product 1 55             Product 2 49            Product 3 16             2014-12

注意:我没有Sql的经验,所以这是我能得到的最好的。

1 个答案:

答案 0 :(得分:1)

您可以使用PIVOT查询来显示上面显示的@temp数据集。

您可以了解如何从here实施PIVOT查询。或者你可以简单地搜索" sql server pivot query"谷歌上的字符串。