具有最大值的组中的特定行

Specific Row in a Group with a Max Value

我有以下 SQL 服务器 table:

+--------+-------+-------+------+
| Person | Phone | Count | Rank |
+--------+-------+-------+------+
|   A    |   X   |   1   |  1   |
|   B    |   X   |   9   |  2   |
|   C    |   X   |   5   |  3   |
|   T    |   Y   |   6   |  1   |
|   S    |   Y   |   2   |  2   |
+--------+-------+-------+------+

我需要结果为 PersonPhone 值,其中 Rank等于1,但是MAX计数值对于具体的Phone例如:

+--------+-------+----------+------+
| Person | Phone | MaxCount | Rank |
+--------+-------+----------+------+
|   A    |   X   |     9    |  1   |
|   T    |   Y   |     6    |  1   |
+--------+-------+----------+------+

我可以加入 table 两次,但想知道我是否可以使用 MAX 来实现这个目标?

您可以使用 MAX(Count)OVER(PARTITION BY Phone),例如 CTE:

WITH CTE AS
(
    SELECT Person, 
           Phone, 
           MaxCount = MAX(Count)OVER(PARTITION BY Phone), 
           Rank
    FROM dbo.TableName
)
SELECT  Person, 
        Phone, 
        MaxCount, 
        Rank
FROM CTE
WHERE Rank = 1

您可以使用子查询:

SELECT T.Person, T.Phone, (SELECT MAX(Count) 
                           FROM YourTable AS TI 
                           WHERE TI.Phone = T.Phone) AS MaxCount, T.[Rank]
FROM YourTable AS T
WHERE T.[RANK] = 1

SQL Fiddle

另一种解决方案是像这样使用 outer apply

SELECT Person, 
       Phone, 
       MaxCount,
       [Rank]
FROM YourTable t1
OUTER APPLY (SELECT MAX([count]) AS MaxCount FROM YourTable WHERE Phone = t1.Phone) oa
WHERE [Rank] = 1