我有一个玩家游戏历史记录表,其中列出了玩家在锦标赛中玩过的所有国际象棋游戏。
CREATE TABLE [dbo].[cub_player_hist](
[id] [int] NOT NULL,
[player_id] [int] NULL, --Player's ID
[Event_Title] [nvarchar](100) NULL,
[Event_id] [int] NULL,
[Event_Start] [smalldatetime] NULL,
[FullName] [nvarchar](max) NULL, -- Player's Name
[Result_txt] [varchar](9) NULL,
[result] [int] NULL,
[played_id] [int] NULL, -- Opponent's ID
[Played] [nvarchar](max) NULL, -- Opponent's Name
CONSTRAINT [cub_player_hist_pk] PRIMARY KEY CLUSTERED
)
我想创建一个View,它将计算每个player_id的playing_id的次数,并为每个playing_id选择最常出现的次数。
如果查看是错误的方法,那么我愿意接受建议!
答案 0 :(得分:1)
为了计算玩家所有比赛的游戏数,以及每个对手的数量,你可以使用SQL COUNT() function with Partition By clause
作为最后一步,为玩家选择最常玩的对手,我们可以使用SQL Row_Number() function with Partition By子句
;with cte as
(
select *,
COUNT(*) over (partition by player_id) cnt_all,
COUNT(*) over (partition by player_id, played_id) cnt_opp
from [dbo].[cub_player_hist]
), cte2 as (
select
*, ROW_NUMBER() over (partition by player_id order by cnt_opp desc) rn
from cte
)
select
player_id,
fullname player_name,
played_id,
played opponent_name
from cte2
where rn = 1
order by player_id