I am running a SQL (mysql) query which results in a table like below and is not stored anywhere Now for each user based on count, I need to fetch the top 3 values. I tried to work with partitions but it fails as result is not in any table.
-----------------------------------------
pkid | username | genre | count|
-----------------------------------------
1 user1 Horror 7
2 user1 Comedy 3
3 user1 Romantic 2
4 user1 Documentary 1
5 user2 Documentary 9
6 user2 Chik-Flick 5
7 user3 Romantic 12
I am trying to get output something like this
------------------------------------------------------------------------
pkid | username | genre1 | count1| genre2| count2 | genre3 | count3
-------------------------------------------------------------------------
1 user1 Horror 7 Comedy 3 Romantic 2
2 user2 Documentary 9 Chik-Flik 5 Null Null
3 user3 Romantic 12 Null Null Null Null
I tried:
WITH temp1 (username,genre,Count1) AS
(<My query which gave result shared>)
SELECT username,genre, Count1
FROM (
SELECT username,genre, Count1
Rank() over (Partition BY username ORDER BY Count1 DESC ) AS Rank
FROM temp1
) WHERE temp1 Rank <= 3
Any Pointers?