SQL Server 中同一子查询的多个聚合
有没有更好的方法来做到这一点,而无需重复的子查询,只选择不同的字段?
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)
正如您所看到的,子查询几乎相同,但只是对不同的行进行求和或计数。我觉得必须有更好的方法来做到这一点,但不知道还能怎么做。我想这可能不是很有效。
如果这个问题已经得到解答,我深表歉意,但我只是想不出一种方法来描述这个问题,所以无法寻找解决方案。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能会起作用:
这只应该扫描票证表一次。
This might do the trick:
This should only scan the ticket table once.
没有测试下一个,但它会是这样的:
Not tested the next one, but it will be something like this: