Reputation: 36850
Is there a straight-forward way in SQL syntax to write this in a single query without a sub-query? And is there any chance in a performance-gain that way?
SELECT ProductCount, COUNT(*) as Occurence
FROM (
SELECT OrderID, COUNT(DISTINCT ProductID) as ProductCount
FROM OrderLine
GROUP BY OrderID
) X
GROUP BY ProductCount
ORDER BY ProductCount
Upvotes: 0
Views: 149
Reputation: 35633
What you have in your question is the recommended way to do it.
You are unlikely to see any performance gain from any change. This is a very common pattern which your database should cope with just fine. If it is slow, consider adding appropriate indexes.
Upvotes: 1