What is the function of the pivot function in MySQL?
In MySQL, there is no built-in PIVOT function, but similar functionality can be achieved using CASE statements and aggregate functions.
The main function of the PIVOT function is to transform multiple rows of data into multiple columns identified by a certain column value. It can transpose the data, turning information that was originally in rows into columns.
For example, consider the data in the following table structure:
Name | Subject | Score
------+----------+-------
John | Math | 90
John | English | 80
John | Science | 85
Amy | Math | 95
Amy | English | 75
Amy | Science | 90
To transpose the above data by subject, you can use the PIVOT function. The transformed result is as follows:
Name | Math | English | Science
------+------+------+--------
John | 90 | 80 | 85
Amy | 95 | 75 | 90
This way, each student’s grades are displayed as a row of data, with each subject’s grades listed in separate columns.
Although MySQL does not have a built-in PIVOT function, you can manually achieve transposition using the CASE statement and aggregate functions. You can refer to the following example code for the specific implementation.
SELECT Name,
MAX(CASE WHEN Subject = 'Math' THEN Score END) AS Math,
MAX(CASE WHEN Subject = 'English' THEN Score END) AS English,
MAX(CASE WHEN Subject = 'Science' THEN Score END) AS Science
FROM TableName
GROUP BY Name;
In the code above, a CASE statement is used to place grades of different subjects into corresponding columns, and the MAX function is used to retrieve the highest grade for each subject. Finally, the data is transposed by using the GROUP BY statement to group by name.
It should be noted that the implementation of the PIVOT function may vary depending on the database, and the code above is just one common implementation method.