【问题标题】:How can I group table by highest record [duplicate]如何按最高记录对表进行分组[重复]
【发布时间】:2014-01-14 09:08:17
【问题描述】:

我有 sql 结果:

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

我怎样才能让它像

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

我的意思是选择每个奖励行获得最多奖励的玩家

【问题讨论】:

    标签: sql group-by greatest-n-per-group


    【解决方案1】:
    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
    

    这个答案假设我们想要每个奖励 id 的记录

    【讨论】:

      【解决方案2】:
      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
      

      【讨论】:

        【解决方案3】:

        试试下面的

        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] 
        

        尝试使用下表。

        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 
        

        它给了我结果

        rewardid    count   playerid
        Burger King  5      1
        KFC          6      2
        

        【讨论】:

        • 看起来很酷。谢谢,但有更好的方法吗?
        • 这不起作用。尝试针对insert into reward values ('BurgerKing', 5, 1), ('BurgerKing', 4, 2), ('KFC', 5, 1), ('KFC', 6, 2) 运行查询。
        • 是的,我找到了。不工作!对不起
        • 用我给的数据集试试。该查询只是意外地使用了 OP 的数据集,因为两组恰好都有 5 个获胜者。如果你让 5 成为赢家,输家成为另一个,输家 5 仍然会出现。
        • @Willie Wheeler 知道了:P。谢谢:)
        猜你喜欢
        • 1970-01-01
        • 2021-04-23
        • 1970-01-01
        • 1970-01-01
        • 2017-03-04
        • 1970-01-01
        • 1970-01-01
        • 2015-02-11
        • 2015-11-16
        相关资源
        最近更新 更多