Skip to content
Advertisement

Transpose Rows to Columns Dynamically in MySQL – Page Rank Per User

I have the following data frame. I want to create a new table with the 4 most viewed pages per user (page and number of times viewed).

So, I need to transpose the following columns: page, quantity and rank.

Note that the variable to order is the rank and not necessarily all the names were in all the pages. Necessarily there must be 4 columns.

Final desired output.

Advertisement

Answer

You can use conditional aggregation:

Demo on DB Fiddle:

id | name | page1  | quantity1 | page2    | quantity2 | page3 | quantity3 | page4    | quantity4
-: | :--- | :----- | --------: | :------- | --------: | :---- | --------: | :------- | --------:
 1 | joan | home   |        15 | search   |         8 | vip   |         4 | checkout |         2
 2 | fill | home   |        20 | vip      |         2 | null  |      null | null     |      null
 3 | mery | search |        10 | checkout |         7 | home  |         5 | null     |      null
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement