简体   繁体   English

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

[英]How to group grouped table T-Sql

I have the following Sql code: 我有以下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

And I get this result: 我得到这个结果:


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

And now, I don't know how to group these rows into one row, for each Period, ie 现在,我不知道如何针对每个期间将这些行分组为一行,即


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

Note: I don't have experience in Sql, so this is the best I can get. 注意:我没有Sql的经验,所以这是我能得到的最好的。

You can use PIVOT query in order to display the @temp dataset as you showed above. 您可以使用PIVOT查询来显示@temp数据集,如上所示。

You can learn how you can implement PIVOT query from here . 您可以从此处了解如何实现PIVOT查询。 Or you can simply search "sql server pivot query" string on google. 或者,您可以在Google上简单地搜索“ SQL Server Pivot查询”字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM