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

时间:2015-01-29 09:29:05

标签: sql-server-2008 tsql max

我有以下 SQL SERVER 表:

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

我需要结果为手机值,其中等级等于1,但 MAX < / strong>特定电话的计数值,例如:

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

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

3 个答案:

答案 0 :(得分:3)

您可以使用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

答案 1 :(得分:3)

您可以使用子查询:

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

答案 2 :(得分:2)

另一种解决方案是使用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