ToTa
ToTa

Reputation: 3334

How to group grouped table T-Sql

I have the following Sql code:

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, i.e.


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.

Upvotes: 0

Views: 73

Answers (1)

aog
aog

Reputation: 504

You can use PIVOT query in order to display the @temp dataset as you showed above.

You can learn how you can implement PIVOT query from here. Or you can simply search "sql server pivot query" string on google.

Upvotes: 1

Related Questions