I would like to select the top 7 categories by spending and then have the rest grouped as 'Others.' It seems like this code works, however it takes at least 20 minutes to run, I think because NOT IN sometimes does not work with indexing.
My database has ~20k records
SELECT [Category], [Total Spending] FROM
(SELECT TOP 7 [Category], SUM([Spending]) AS [Total Spending]
FROM Data
GROUP BY [Category]
ORDER BY SUM([Spending]) DESC
) AS Q1
UNION ALL
SELECT'Other' AS [Category], SUM(Spending) AS [Total Spending]
FROM Data
WHERE Category NOT IN
(SELECT TOP 7 [Category]
FROM Data
GROUP BY [Category]
ORDER BY SUM([Spending]) DESC)
My Question is a combination of these two questions, both answered: