Is there a better way of doing this without having the repeated sub queries that just select a different field?
SELECT Name, er.DateEventStarts, e.LocationName,
(SELECT count(*) FROM Ticket t WHERE t.Deleted = 0 AND Refunded = 0 AND t.EventRepetitionID = er.EventRepetitionID) AS NoOfAttendees,
(SELECT sum(t.TicketTotalCost) FROM Ticket t WHERE t.Deleted = 0 AND Refunded = 0 AND t.EventRepetitionID = er.EventRepetitionID) AS NoOfAttendees,
(SELECT sum(t.OnlinePayFee) FROM Ticket t WHERE t.Deleted = 0 AND Refunded = 0 AND t.EventRepetitionID = er.EventRepetitionID) AS OnlinePayFee,
(SELECT sum(t.OnlinePayTotalCost) FROM Ticket t WHERE t.Deleted = 0 AND Refunded = 0 AND t.EventRepetitionID = er.EventRepetitionID) AS OnlinePayTotalCost
FROM [Event] e
JOIN EventRepetition er ON er.EventRepetitionID = (SELECT TOP 1 EventRepetitionID FROM EventRepetition er2 WHERE er2.EventID = e.EventID)
As you can see the sub queries are almost the same but just sum or count a different row. I feel there must be a better way of doing this but can’t see how else to do it. I imagine this is probably not very efficient.
I apologise if this has already been answered but I just cannot think of a way to describe this problem so was unable to search for a solution.
This might do the trick:
This should only scan the ticket table once.