【问题标题】:How to select 6 top records of each individual records at the database when selecting from all rows从所有行中选择时如何在数据库中选择每个单独记录的 6 个顶部记录
【发布时间】:2016-03-16 23:27:28
【问题描述】:

假设我有下表

CREATE TABLE #tblUsersPokemons (
    RecordId int NOT NULL,
    PokemonId int NOT NULL,
    PokemonExp int NOT NULL,
    PokemonLevel int NOT NULL,
    UserId int NOT NULL
)

现在下面的查询可以正常工作了

select 
  SUM(cast(PokemonExp as bigint)) as TotalExp,
  MAX(PokemonLevel) as MaxPokeLevel,
  Count(PokemonId) as TotalPoke,
  UserId 
from #tblUsersPokemons 
group by UserId

这里是此类查询的示例结果

ToplamExp   MaxPokeLevel    TotalPoke   UserId
----------- --------------- ----------- --------
29372294    101             4           1
1134696     98              1           2
1400        98              1           101
24534365    98              4           102
1400        98              1           1102
1400        98              1           1103
1400        98              1           2102
1400        98              1           2103
789220      98              7           2105
1468        98              1           3104

现在我的问题来了

我想限制计数的 PokemonId。我的意思是我想选择最多 6 个相同的 PokemonId 记录。从这些记录中,PokemonExp 排序的前 6 名应该被计算在内。

例如用户有以下记录

从这个表中查询应该采用记录 id : 1,2,3,4,5,6,9 而不是 7,8,因为 PokemonId 1 的前 6 条记录被采用

【问题讨论】:

    标签: sql sql-server tsql sql-server-2014


    【解决方案1】:

    如果我理解正确,您希望每个用户的前 6 行聚合。您可以使用row_number() 轻松做到这一点:

    select SUM(cast(PokemonExp as bigint)) as ToplamExp,
           MAX(PokemonLevel) as MaxPokeLevel,
           Count(PokemonId) as TotalPoke,UserId 
    from (select p.*,
                 row_number() over (partition by userid order by pokemanexp desc) as seqnum
          from tblUsersPokemons p
         ) p
    where seqnum <= 6
    group by UserId;
    

    编辑:

    我想你想在partition by 子句中包含PokemonId

    select SUM(cast(PokemonExp as bigint)) as ToplamExp,
           MAX(PokemonLevel) as MaxPokeLevel,
           Count(PokemonId) as TotalPoke,UserId 
    from (select p.*,
                 row_number() over (partition by userid, PokemonId
                                    order by pokemanexp desc) as seqnum
          from tblUsersPokemons p
         ) p
    where seqnum <= 6
    group by UserId;
    

    【讨论】:

    • ty 用于回答,但不是针对每个用户 ID。对于每个 pokemonid,这些 pokemonids 需要按 pokemonexp 记录 desc 排序。所以会拿走拥有口袋妖怪的最大EXP。我现在将尝试应用您的答案:D
    • 嘿,我还有一个问题。您使用 select p.* 是必须的吗?如果您认为表是 50 列但我们只需要 5 列,它会导致性能下降吗?非常喜欢
    • @MonsterMMORPG 。 . . SQL Server 应该足够聪明,可以优化掉子查询中不需要的列。当然,明确列出您需要的列始终是一种好习惯,但我认为在这种情况下它不会对性能产生影响。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2010-10-18
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多