开发者

Multiple aggregates from same sub query in SQL Server

开发者 https://www.devze.com 2023-04-02 03:40 出处:网络
Is there a better way of doing this without having the repeated sub queries that just select a different field?

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 = e开发者_运维知识库r.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:

SELECT
    Name,
    er.DateEventStarts,
    e.LocationName,
t.NoOfAttendees,
t.TotalTickets,
t.OnlinePayFee,
t.OnlinePayTotalCost  
FROM [Event] e
JOIN EventRepetition er
    ON
        er.EventRepetitionID = (SELECT TOP 1 EventRepetitionID FROM EventRepetition er2 WHERE er2.EventID = e.EventID)
join
    (select EventRepetitionID,COUNT(*),SUM(TicketTotalCost),SUM(OnlinePayFee),SUM(OnlinePayTotalCost)
    from Ticket
    where Deleted = 0 and Refunded = 0
    group by EventRepetitionID) t (EventRepetitionID,NoOfAttendees,TotalTickets,OnlinePayFee,OnlinePayTotalCost)
        on
            er.EventRepetitionID = t.EventRepetitionID

This should only scan the ticket table once.


Not tested the next one, but it will be something like this:

select Q.name, Q.ateEventStarts, Q.locationName,
        count(*), sum(T.TicketTotalCost), sum(T.TicketTotalCost), 
        sum(T.OnlinePayFee), sum(T.OnlinePayTotalCost)
    from ( 
        select Name, er.DateEventStarts, e.LocationName, er.EventRepetitionID
            from Event e JOIN EventRepetition er on er.EventRepetitionID = 
                (select top 1 EventRepetitionID from         
                    EventRepetition er2 where er2.EventID = e.EventID) ) Q
    left outer join Ticket T
        on t.Deleted = 0 and T.Refunded = 0 
            and t.EventRepetitionID = Q.EventRepetitionID
0

精彩评论

暂无评论...
验证码 换一张
取 消