计算最高评级值的数量

时间:2015-01-12 04:47:31

标签: sql sql-server

我有一个表FixtureStats

Id    FixtureId    PlayerID Rating    other Attributes
1       1              1      8.5
2       1              2      6.8
3       1              3      9.1   << man of the match(Motm) 
.....
100     4              1      5.3
101     4              2      7.6     << Motm
102     4              3      4.5

我想选择一个玩家列表以及Motm one的数量。

例如

    PlayerId   Motm

     1          0
     2          1
     3          1

谢谢大家。

2 个答案:

答案 0 :(得分:3)

您可以使用ROW_NUMBER()功能:

;with cte AS (SELECT *
                    ,CASE WHEN ROW_NUMBER() OVER(PARTITION BY FixtureID ORDER BY Rating DESC) = 1 THEN 1 END AS Motm
              FROM FixturStats
             )
SELECT PlayerID
      ,SUM(Motm) AS Motm
FROM cte
GROUP BY PlayerID

由于您只关心Motm我将其CASE包裹在1中,因此它可以是NULLCASE,然后可以简单地汇总。如果您想查看某人是第二名或第三名的频率,您可以删除ROW_NUMBER()并以不同方式进行汇总。

PARTITION BY为由ORDER BY确定的组中的每一行创建一个数字,并根据rating进行编号,在这种情况下,您需要来自FixtureID的顶部{{1}}每个{{1}},我们都会使用这些。

答案 1 :(得分:2)

您可以使用ROW_NUMBER()

WITH CTE AS(
    SELECT
        *,
        rn = ROW_NUMBER() OVER(PARTITION BY FixtureId ORDER BY Rating DESC)
    FROM FixtureStats
)
SELECT
    p.PlayerID,
    Motm = COUNT(c.PlayerID)
FROM (
    SELECT DISTINCT PlayerID FROM FixtureStats
)p
LEFT JOIN CTE c
    ON c.PlayerID = p.PlayerID
    AND c.rn = 1
GROUP BY p.PlayerID