SQL row and column conversions

Source: Internet
Author: User

  1. First we set up a table, named Rtoc, each field of the design such as, respectively, is Name,course,score, representing the name, scores and scores,.

  2. 2

    We added data to the table to add Xiao Ming and floret of the language and math scores.

  3. 3

    Next, we're going to do a row-and-column conversion, which should be name, language, math. We first have to consider how to get the column names, we can get the course name by grouping. , we can see the stitching string of the course name from the query result through the grouping statement.

    Code:

    Declare @sql varchar ($) Select @sql = ISNULL (@sql+',',') +  from Group  by Course Select @sql

    Effect:

  4. 4

    Next, the key row-to-column function pivot comes out, through which we populate the fractions into the converted column-language, mathematical column values.

    Declare @sql varchar( $)Select @sql=ISNULL(@sql+',',"')+Course fromRtocGroup  byCourseSet @sql='SELECT * from Rtoc pivot (max (score) for course in ('+@sql+')) T'  exec(@sql)
  5. 5

    After we run, we can get the result of the row-to-column, as shown in.

  6. 6

    Through the above steps, we can easily achieve the transformation of the ranks. Similarly, what should we do if we want to convert the columns into rows? We can also use the Unpivot function as an easy implementation.

SQL row and column conversions

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.