0

I have sql results:

+----------+-----+--------+
|rewardID  |count|playerID|
+----------+-----+--------+
|BurgerKing|5    |1       |
+----------+-----+--------+
|BurgerKing|4    |2       |
+----------+-----+--------+
|KFC       |1    |1       |
+----------+-----+--------+
|KFC       |5    |2       |
+----------+-----+--------+

how can i make it to be like

+----------+-----+--------+
|rewardID  |count|playerID|
+----------+-----+--------+
|BurgerKing|5    |1       |
+----------+-----+--------+
|KFC       |5    |2       |
+----------+-----+--------+

I mean select player who get most reward for each reward row

ekad
  • 14,436
  • 26
  • 44
  • 46
user3193307
  • 503
  • 1
  • 4
  • 8

3 Answers3

0

Try the below

select Y.rewardId,Y.count,[playerId] from YourTable Y
join (select [rewardId],MAX([count]) as [count] from YourTable group by [rewardId]) as Y1
on Y.rewardId=Y1.rewardId and Y.[count]=Y1.[count] 

Tried with the following table.

CREATE TABLE [dbo].[yourtable]( [rewardid] [nvarchar](50) NULL, [count] [int] NULL, [playerid] [int] NULL )
INSERT INTO [dbo].[yourtable] ([rewardid] ,[count] ,[playerid])
VALUES ('Burger King', 5,1), ('Burger King', 4,2), ('KFC',1,1), ('KFC',6,2) GO 

And it gave me result

rewardid    count   playerid
Burger King  5      1
KFC          6      2
Naveen
  • 1,496
  • 1
  • 15
  • 24
  • it seems cool . thanks but any way better? – user3193307 Jan 14 '14 at 09:24
  • This doesn't work. Try running the query against `insert into reward values ('BurgerKing', 5, 1), ('BurgerKing', 4, 2), ('KFC', 5, 1), ('KFC', 6, 2)`. –  Jan 14 '14 at 09:30
  • yeah i found it. doesnt work ! sorry – user3193307 Jan 14 '14 at 09:31
  • Are you sure? I just tried and it is giving me proper result. – Naveen Jan 14 '14 at 09:33
  • 1
    Try it with the dataset I gave. The query is just accidentally working with the OP's dataset because both groups happen to have 5 as the winner. If you make 5 the winner for one and the loser for the other, the loser 5 will still show up. –  Jan 14 '14 at 09:35
  • Try with KFC,5,1 and KFC,6,2. Not KFC,1,1 and KFC,6,2. :-) –  Jan 14 '14 at 09:36
  • @Willie Wheele I have updated the answer. I hope it will work for all scenario. – Naveen Jan 14 '14 at 10:30
0
select yourtable.rewardid,yourtable.count,yourtable.playerid  from yourtable left join (select distinct rewardid, max(count) OVER (PARTITION BY rewardid)  as maxcount from yourtable) source 
on source.rewardid=yourtable.rewardid and source.maxcount=yourtable.count where source.maxcount is not null

This answer is assuming that we want records for each reward id

DhruvJoshi
  • 17,041
  • 6
  • 41
  • 60
0
select t.rewardId,t.count,playerId from tableName as t    
join 
(select rewardId,MAX([count]) as cnt 
 from tableName
 group by rewardId
) as t1
on t.rewardId=t1.rewardId and t.count=t1.cnt
Naveen
  • 1,496
  • 1
  • 15
  • 24
Dharmesh
  • 132
  • 1
  • 12