I have the following (fairly legacy, did this a year or two ago) SQL query. The webpage the SQL is on (used on an SqlDataSource/GridView in ASP.NET) is very slow, and I’ve pinpointed the slowness to this query – seemingly because of the sub select. I’ve tried using joins to hopefully speed it up but I can’t get it to work. Any ideas?
I won’t put the whole query here, simply because I work on a machine with no internet access so I won’t be able to copy and paste, and most of it is just selecting from the main table.
SELECT ...,
CASE
WHEN di.Total = di.Delivered THEN 'Received'
ELSE 'Not Received' END AS 'Status',
...
FROM Deliveries AS d
LEFT OUTER JOIN (
SELECT Delivery,
COUNT(*) AS Total,
COUNT(CASE WHEN Status = 2 THEN 1 END) AS Delivered
FROM DeliveryItems
GROUP BY Delivery
) AS di ON d.ID = di.Delivery
Any tips?
This part could be improved by ditching that CASE statement. Maybe try joining twice, once against the total count and once against the filtered count.