Reputation: 2184
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.
Upvotes: 0
Views: 5469
Reputation: 7093
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
Upvotes: 1
Reputation: 69749
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
Upvotes: 2
Reputation: 6194
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
Upvotes: 1