Table with 2 column data forming primary key converted to 1 column as primary key

Source: Internet
Author: User

Question: Suppose there is a student score table (TB) as follows:
Name Course Score
Zhang San language 74
Zhang San Mathematics 83
Zhang San Physics 93
Zhang Sande language null
John Doe Language 74
John Doe Mathematics 84
John Doe Physics 94
John Doe English 80
Want to become (get the following result):
Name Chinese mathematics Physics English German
---- ---- ---- ----
Lee 474 84 94? 60
Zhang 374 83 93 80?

Here name and course determine only one record, as the primary key.

After conversion only the name as the primary key, the specific value of the other primary key is made a field, it is not difficult to understand, a horizontal course value and an ordinate name value can uniquely determine a record.

Use case when to implement the following

Select Name,
SUM (case when course= "let" then score else 0 end) Let,
SUM (case if course= ' math ' then score else 0 end) Math,
SUM (case if course= ' PHY ' then score else 0 end) PHY,
SUM (case if course= ' Eng ' then score else 0 end) Eng,
SUM (case if course= ' ger ' then score else 0 end) GER
From grade
Group BY name

Here the SUM function can be replaced with Max (), and the purpose of using the function is to use the Casewhen statement to generate a column.

Casewhen Simple explanation: According to name and course Find score value fill table, if NULL is set to 0;

Group BY is a required statement, otherwise the record has only one, name is the first of the table • The name of the record.

The result after execution is

Table with 2 column data forming primary key converted to 1 column as primary key

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.