从所有行中进行选择时,如何从数据库中选择6条顶级记录

时间:2014-08-14 14:28:18

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

假设我有下表

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

现在我的问题来了

我想限制计算的PokemonIds。我的意思是我想选择每个相同的PokemonId记录中的最多6个。从这些记录中,PokemonExp排名前6位的desc应计入。

例如,用户具有以下记录

enter image description here

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

1 个答案:

答案 0 :(得分:4)

如果我理解正确,您希望每个用户排在前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;

编辑:

我认为您希望在PokemonId子句中包含partition by

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;