DROP TABLE #game_stats
CREATE TABLE #game_stats (gamename VARCHAR(50),users VARCHAR(50),times_played INT);
INSERT INTO #game_stats VALUES ('Counter Strike','Kamesh',2);
INSERT INTO #game_stats VALUES ('Counter Strike','Hely',4);
INSERT INTO #game_stats VALUES ('Counter Strike','Maitri',1);
INSERT INTO #game_stats VALUES ('Counter Strike','Laxmi',5);
INSERT INTO #game_stats VALUES ('WOW','Kamesh',21);
INSERT INTO #game_stats VALUES ('WOW','laxmi',60);
INSERT INTO #game_stats VALUES ('WOW','Hely',7);
INSERT INTO #game_stats VALUES ('NFS','Hely',5);
INSERT INTO #game_stats VALUES ('NFS','Kamesh',1);
INSERT INTO #game_stats VALUES ('NFS','Maitri',12);
INSERT INTO #game_stats VALUES ('NFS','Laxmi',21);
INSERT INTO #game_stats VALUES ('CODE ZERO','Kamesh',45);
INSERT INTO #game_stats VALUES ('CODE ZERO','Maitri',52);
INSERT INTO #game_stats VALUES ('CODE ZERO','Laxmi',21);
INSERT INTO #game_stats VALUES ('CODE ZERO','Kamesh',41);
INSERT INTO #game_stats VALUES ('HITMAN','Maitri',142);
INSERT INTO #game_stats VALUES ('HITMAN','Laxmi',210);
INSERT INTO #game_stats VALUES ('HITMAN','Kamesh',41);
INSERT INTO #game_stats VALUES ('HITMAN','Maitri',102);
INSERT INTO #game_stats VALUES ('HITMAN','Mani',142);
INSERT INTO #game_stats VALUES ('NFS','Mani',210);
INSERT INTO #game_stats VALUES ('CODE ZERO','Mani',41);
INSERT INTO #game_stats VALUES ('WOW','Mani',102);
select * from #game_stats;
SELECT RN,
Gamename,
Users,
Times_played
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY GS.gamename ORDER BY SUM(GS.times_played) DESC) AS RN,
GS.gamename,
GS.users,
SUM(gs.times_played) as times_played
FROM #game_stats GS
WHERE GS.gamename IN (
SELECT TOP 3 gamename
FROM #game_stats
GROUP BY gamename
ORDER BY sum(times_played) DESC
)
GROUP BY GS.gamename,GS.users
) a
WHERE RN<=3
ORDER BY gamename,times_played DESC