To create a table:
IF object_id (' t040_product_sales ') is not nulldrop table T040_product_salescreate table T040_product_sales (ID INT IDENTI TY ( ProductName VARCHAR), salemonth int, salescount int)
Insert data and Sort:
INSERT into T040_product_sales VALUES (' Bicycle ', (), (' Shoes ', 2,2), (' Clothes ', 3,3), (' Books ', "bis"), (' Medicine ', 5,5) , (' drinks ', 6,6), (' Shoes ', 7,7), (' Books ', ","), (' Bicycle ', 1,3), (' Medicine ', 1,4), (' Clothes ', 1,5), (' Mobile Phone ', 1,6), (' Books ', 1,7), (' Medicine ', 1,8), (' Shoes ', 1,9), (' Bicycle ', 2,10) SELECT ProductName, salemonth, SUM ( Salescount) as Salescountfrom t040_product_salesgroup by ProductName, Salemonthorder by ProductName, Salemonth
Format:
/****select Non-pivot column, [pivot column 1] as ' column name 1 ', [pivot column 2] as ' column Name 2 ', [pivot column 3] as ' column name 3 ' from ( --source data SELECT non-pivot column, transparent Depending on the column value of the source column, you need to aggregate the value from table ) as alias pivot ( SUM (value to aggregate) for Pivot column value source column in ([Pivot column 1],[pivot column 2],[pivot column 3 ]) as alias ****/
Line-to-column code:
Select ProductName, ISNULL ([1],0) as ' 1 ', ISNULL ([2],0) as ' 2 ', ISNULL ([3],0) as ' 3 ', ISNULL ([4],0) as ' 4 ', ISNULL ([5],0) as ' 5 ', ISNULL ([6],0) as ' 6 ' from (select ProductName, salemonth, salescount From T040_product_sales) as SALES pivot (SUM (salescount) for Salemonth in ([1],[2],[3],[4],[5],[6])) as pivotbl
Results:
Pivot row-to-column pivot operation in SQL Server