• + 6 comments

    The logic of this query is:

    1. Reshpe Occupation into 4 columns with their index in each occupation, this leads to Temp table (which has many NULL).
    2. Then group Temp by index and select corresponding Name for each Occupation.

    min()/max() will return a name for specific index and specific occupation. If there is a name, it will return it, if not, return NULL.

    You can just run the Temp table to see what it looks like, don’t forget to include set statement. It will be very helpful if you break down the code and see the result.

    I did not find tutorial using similar schema, but Pivot a table in MySQL, and these two answers on StackOverflow MySQL - Rows to Columns (with detailed explanation), and MySQL get first non null value after group by help me reslove this problem.