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.
WITH TIES
offers a cleaner way to get all offices sharing the top count:There are a number of approaches:
OR
OR
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