Select row with max value in one column

2019-09-04 02:38发布

I have a select statement that returns two columns: office names and total per 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

How can I get the row that has max total? "Customers" table has an "OfficeID" colummn. For a given "ClusterID", I select all offices within the cluster identified by cluster id (e.g. 29) and count the customers belongin to those offices.

3条回答
祖国的老花朵
2楼-- · 2019-09-04 02:39

WITH TIES offers a cleaner way to get all offices sharing the top count:

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
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-09-04 02:45

There are a number of approaches:

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

OR

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)

OR

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

Although using TOP 1 may not be what you are after, with the other methods if there are 2 offices with the same number of customers they will both be returned, whereas TOP 1 will only return 1 of these (probably in order of office name). If you only ever want 1 record, then this is the best method

查看更多
Luminary・发光体
4楼-- · 2019-09-04 02:46
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
查看更多
登录 后发表回答