Coordinated subqueries are slow. When you add in aggregating the data, then
they are even slower.
First, make sure you have indexes on all the relevant fields. In my example
that would be storeid and customerid.
You can test if the query is working by adding a where clause that restricts
the query to just one store
SELECT Distinct StoreID, CustomerID
FROM Purchases as P
WHERE CustomerID in
(SELECT TOP 100 CustomerID
FROM Purchases as P1
WHERE P1.StoreID = P.StoreID
GROUP BY CustomerID
ORDER BY Sum(AmountsPurchased) DESC, CustomerID)
WHERE P.StoreID = 121
You can also try nesting queries. This might be faster.
Save the following as qOne
SELECT StoreID, CustomerID
, Sum(AmountsPurchased) as TotalPurchase
FROM Purchases
GROUP BY StoreID, CustomerID
Then use that saved query
SELECT Distinct StoreID, CustomerID
FROM Purchases as P
WHERE CustomerID in
(SELECT TOP 100 CustomerID
FROM qOne
WHERE qOne.StoreID = P.StoreID
ORDER BY TotalPurchase DESC, CustomerID)