Count total rows with a group by Count total rows with a group by sql-server sql-server

Count total rows with a group by


SELECT COUNT(*)FROM (   SELECT TRACKING_NUM   FROM Orders   GROUP BY TRACKING_NUM   HAVING count(distinct ORDER_NUM) = 4) AS Agg


SELECT OrderCount AS 'Total Orders', COUNT(TRACKING_NUM) AS 'Tracking Num Count' FROM (   SELECT DISTINCT TRACKING_NUM, COUNT(DISTINCT ORDER_NUM) AS 'OrderCount'   FROM Orders   GROUP BY TRACKING_NUM) AS tblOrdersPerTrackingNum

This will get you just the counts for your TRACKING_NUMs like you wanted, and also get the counts for every other amount of total orders (not just having order count = 4).

(It sounds like your query is for some kind of a report -- if that is the case, and if it will run often where performance is a concern, as you suggested -- you might as well get all of your values from one query, instead of changing or parameterizing the count that your are interested in and re-running it multiple times (even if that were automated). Much better to let the server do it all for you once. Forgive my assumption if that is not what you were working towards.)

I know that's not exactly what you were asking about... Remus Rusanu already nailed that, but you did ask for "any suggestions".