An Implementation Method for SQL Server row-to-column Conversion

Source: Internet
Author: User

For some businesses, the storage of data in the table is exactly the same as the final result of reversing the source table. At this time, we encountered the problem of converting rows into columns, to simplify the problem, you do not have to worry about the table design and SQL statements as follows:

The source table is as follows: (The table name is info)

 

------------------------------------------------------------------------

SelectUsername,   

Language = (CaseCourseWhen 'China' ThenGradeElse0End),   

Mathematics = (CaseCourseWhen 'Mat' ThenGradeElse0End),  

Politics = (CaseCourseWhen 'Politics' ThenGradeElse0End)

FromInfo

Let's look at our execution results:

After seeing this, we all know what we should do, group, group by name, and sum the three courses separately;

------------------------------------------------------------------------

Target results:

 

The SQL statement is:

Select username,   Language = sum (Case course when 'China' then grade else 0 end ),   Math = sum (Case course when 'mate' then grade else 0 end ),   Politics = sum (Case course when 'state' then grade else 0 end) from Info group by username

SelectUsername,   

Language =Sum(CaseCourseWhen 'China' ThenGradeElse0End),  

Mathematics =Sum(CaseCourseWhen 'Mat' ThenGradeElse0End), 

Politics =Sum(CaseCourseWhen 'Politics' ThenGradeElse0End)

FromInfo

GroupUsername

 

 

Related Article

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.