Conversion between SQL Server rows and columns

Source: Internet
Author: User
SQL Server converts rows to columns: for example, if a table contains only a small amount of data, you can use static SQL statements such as selectstuName and max (caseCoursewhen language thenscoreelse0end) as language, max (caseCoursewhen math thenscoreelse0end) as math, max (caseCoursewhen

SQL Server transfers rows to columns, as shown in the following table: When a table contains only a small amount of data, you can use static SQL statements such as select stuName, max (case Course when 'then score else 0 end) as language, max (case Course when 'mate' then score else 0 end) as mathematics, max (case Course when'

SQL Server converts rows to columns:

See the following table:

When a table contains only a small amount of data, you can use static SQL statements.

For example:

Select stuName,
Max (case Course when 'China' then score else 0 end) as language,
Max (case Course when 'mate' then score else 0 end) as mathematics,
Max (case Course when 'then score else 0 end) as English,
Max (case Course when 'physical 'then score else 0 end) as physical,
Sum (score) as 'Total'
From Student group by stuName

When a data table contains a large amount of data, dynamic SQL statements must be used.

Follow these steps:

Declare @ name varchar (8000) -- declare a variable
Set @ name = 'select stuname'
Select @ name = @ name + ', sum (case Course when ''' + Course + ''' then score else 0 end) [' + Course + ']'
From (select distinct Course from Student) as
Set @ name = @ name + 'from Student group by stuname'
Exec (@ name)

The distinct keyword is used to filter out redundant duplicate records and retain only one record, but it is often used to return the number of records that do not repeat, instead of returning all values that do not record duplication.

The above two results are the same, and the results are as follows:

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.