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