• + 0 comments

    /* MySQL*/ select max(case when occupation = 'Doctor' then name else null end) as 'Doctor', max(case when occupation = 'Professor' then name else null end) as 'Professor', max(case when occupation = 'Singer' then name else null end) as 'Singer', max(case when occupation = 'Actor' then name else null end) as 'Actor' from (select occupation, name, row_number() over (partition by occupation order by name) as rn from occupations) as pn group by rn; /* * The query starts with a subquery that selects the occupation, name, and row_number() values from the occupations table, grouped by occupation and ordered by name.

    • The row_number() function is used to assign a unique sequential number to each row within its partition. This is important because it allows the query to group the rows by their rn value later on.

    • The outer query uses the max() function with a case expression for each occupation to pivot the data into separate columns.

    • The case expression checks whether the occupation value matches the specified occupation and returns the name value if it does. Otherwise, it returns null.

    • The max() function then selects the maximum name value for each occupation, ignoring any null values. The as keyword is used to assign aliases to each of the resulting columns.

    Finally, the group by clause is used to group the rows by their rn value, which effectively transposes the data from rows to columns. */