在一列中选择具有最大值的行

时间:2012-03-03 07:15:18

标签: sql-server-2008 max

我有一个select语句,它返回两列:office名称和每个办公室的总数:

select o.OfficeName, c.Total
from Offices o
left join
( select OfficeID, count(*) Total
from Customers c
group by OfficeID
) c on o.OfficeID = c.OfficeID
where o.ClusterID = 29

如何获得最大总数的行? “Customers”表有一个“OfficeID”列。对于给定的“ClusterID”,我选择由群集ID标识的群集中的所有办公室(例如29),并计算属于这些办公室的客户。

3 个答案:

答案 0 :(得分:2)

有很多方法:

SELECT  OfficeName, Total
FROM    (   SELECT  o.OfficeName, c.Total, MAX(Total) OVER() [MaxTotal]
            FROM    Offices o
                    LEFT JOIN
                    (   SELECT  OfficeID, COUNT(*) Total
                        FROM    Customers
                        GROUP BY OfficeID
                    ) c 
                        ON o.OfficeID = c.OfficeID
            WHERE   o.ClusterID = 29
        ) c
WHERE   Total = MaxTotal

WITH CTE AS
(   SELECT  o.OfficeName, c.Total
    FROM    Offices o
            LEFT JOIN
            (   SELECT  OfficeID, COUNT(*) Total
                FROM    Customers
                GROUP BY OfficeID
            ) c 
                ON o.OfficeID = c.OfficeID
    WHERE   o.ClusterID = 29
)
SELECT  *
FROM    CTE
WHERE   Total = (SELECT MAX(Total) FROM CTE)

SELECT  TOP 1 o.OfficeName, c.Total
FROM    Offices o
        LEFT JOIN
        (   SELECT  OfficeID, COUNT(*) Total
            FROM    Customers
            GROUP BY OfficeID
        ) c 
            ON o.OfficeID = c.OfficeID
WHERE   o.ClusterID = 29
ORDER BY Total DESC

虽然使用TOP 1可能不是你想要的,但是如果有2个办公室拥有相同数量的客户,那么他们将被退回,而TOP 1将只返回其中的1个(可能是按顺序办公室名称)。如果你只想要1条记录,那么这是最好的方法

答案 1 :(得分:1)

SELECT TOP 1 o.OfficeName, c.Total
  FROM Offices o
  LEFT JOIN
    (SELECT OfficeID, count(*) Total
       FROM Customers c
      GROUP BY OfficeID
    ) c ON o.OfficeID = c.OfficeID
 WHERE o.ClusterID = 29
 ORDER BY c.Total DESC

答案 2 :(得分:1)

WITH TIES提供了一种更清晰的方式来让所有办公室分享最高分数:

with a as (
    select o.OfficeID,Total=COUNT(*)
    from Offices o
    inner join Customers c on c.OfficeID=o.OfficeID
    group by o.OfficeID
)
select top 1 WITH TIES t.OfficeName, a.Total
from a
inner join Offices t on t.OfficeID=a.OfficeID
where t.ClusterID=29
order by a.Total desc