How to convert Column records recorded in the database into rows under sqlserver

Source: Internet
Author: User

Assume that there is a student renewal table (tb) as follows:
Name Subject Result
Zhang San Language 74
James math 83
Zhang San physical 93
Li Si language 74
Li Si mathematics 84
Li Si physical 94
Want to become

Name, Chinese, Mathematics, Physics
-------------------------------------------
Li Si 74 84 94
Zhang San 74 83 93
The SQL statement is as follows:
Copy codeThe Code is as follows:
Create table tb
(
Name varchar (10 ),
Subject varchar (10 ),
Result int
)
Insert into tb (Name, Subject, Result) values ('zhang san', 'China', 74)
Insert into tb (Name, Subject, Result) values ('zhang san', 'mat', 83)
Insert into tb (Name, Subject, Result) values ('zhang san', 'Physical ', 93)
Insert into tb (Name, Subject, Result) values ('Li si', 'China', 74)
Insert into tb (Name, Subject, Result) values ('lily', 'mat', 84)
Insert into tb (Name, Subject, Result) values ('lily', 'Physical ', 94)
Go

-- Static SQL indicates that subject has only three courses: Chinese, mathematics, and physics.
Select name,
Max (case Subject when 'China' then result else 0 end) language,
Max (case Subject when 'mate' then result else 0 end) math,
Max (case Subject when 'physical 'then result else 0 end) Physical
From tb
Group by name

-- Dynamic SQL refers to subject more than three courses: Chinese, mathematics, and physics.

Declare @ SQL varchar (8000)
Set @ SQL = 'select Name as '+ 'name'
Select @ SQL = @ SQL + ', max (case Subject when ''' + Subject + ''' then Result else 0 end) [' + Subject + ']'
From (select distinct Subject from tb) as
Set @ SQL = @ SQL + 'from tb group by name'
Exec (@ SQL)

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.