SQL displays rows as columns

Source: Internet
Author: User

When I wrote this article, I referred to the book "SQL hacks", which uses SQL Server 2008.

For example, there is a table

create table  tbCourseGrade(student varchar(10)  , course varchar(10)  , grade int )

Then there are some records:

Insert into tbcoursegrade (student, course, grade) values ('James ', 'high number', 98), ('James', 'English ', 56), ('James ', 'China', 77), ('small red', 'high data', 89), ('small red', 'English ', 88), ('xiaoming', 'China ', 67)

Insert into tbcoursegrade (student, course, grade) values ('millet ', 'high number', 55)

The displayed information should be:

Student Course grade

James is 98

James English 56

*****

Red up to 89

*****

Millet high 55

Then how can it be displayed

English Language

James 98 56 77

Xiaohong ******

Xiaomi 55 null

This is a common problem: displaying rows as columns !!!

The following two methods are provided:

1. Connect yourself four times

Select yuan. student as name, gaoshu. grade as high, yingyu. grade as English, Yuwen. grade as language from tbcoursegrade as yuanleft join tbcoursegrade as gaoshu on (Yuan. student = gaoshu. student and gaoshu. course = 'high') left join tbcoursegrade as yingyuon (Yuan. student = yingyu. student and yingyu. course = 'English ') left join tbcoursegrade as yuwenon (Yuan. student = Yuwen. student and Yuwen. course = 'China ')

2. Use Case statements

Select yuan. student as name, max (case when Hou. course = 'high number' then Hou. gradeelse nullend) as high score, max (case when Hou. course = 'English 'Then Hou. gradeelse nullend) as English score, max (case when Hou. course = 'China' then Hou. grade else nullend) as language score from tbcoursegrade as Yuan join tbcoursegrade as Hou on Yuan. student = Hou. studentgroup by Yuan. student

When you look at the above two methods, you may think why left join and Max are used. If you don't understand it, you can remove left and max. From the result, you will understand.

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.