Pivot row-to-column pivot operation in SQL Server

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.