我有这个查询,我需要从3个表中提取数据,但是有一些分组需要发生。我知道子查询很糟糕,但我似乎无法以任何其他方式完成此操作。当有数十万行时,这将会崩溃。也许我过于复杂了?我尝试了“分区依据”,但是这会从ERT1中拉回所有行,这会弄乱计数。我不能使用一个组,因为如果我在ERT1上分组,它会搞乱ER1。
我在加入的字段中使用FK和索引。
有人对此有任何想法吗?
非常感谢!!
SELECT ER.EventRegistrationID, DC.DiscountCodeID, DC.DiscountAmount, DC.DiscountCode, DC.ActiveFlag,
ISNULL((SELECT COUNT(ER1.EventRegistrationID)
FROM T_EventRegistration ER1
WHERE ER1.DiscountCode = DC.DiscountCode
AND ER1.EventID = DC.EventID
AND ER1.OrderCompleteFlag = 1),0) AS NumTimesUsed, --includes refunded orders
ISNULL((SELECT COUNT(ERT1.TicketNumber)
FROM T_EventRegistrationTickets ERT1, T_EventRegistration ER1
WHERE ER1.EventRegistrationID = ERT1.EventRegistrationID
AND ER1.DiscountCode = DC.DiscountCode
AND ER1.EventID = DC.EventID
AND ER1.OrderCompleteFlag = 1
),0) AS NumTicketsSold --excludes refunded tickets
FROM T_DiscountCodes DC, T_EventRegistration ER
WHERE DC.DiscountCode *= ER.DiscountCode
AND DC.EventID = 20188
AND DC.DeleteFlag = 0
AND DC.HiddenFlag = 0
AND ER.OrderCompleteFlag = 1
ORDER BY DC.DiscountCode, NumTimesUsed
答案 0 :(得分:1)
您可以使用APPLY或创建派生表
来完成此操作SELECT ER.EventRegistrationID
, DC.DiscountCodeID
, DC.DiscountAmount
, DC.DiscountCode
, DC.ActiveFlag
, ISNULL(a,NumTimesUsed,0)
, ISNULL(a2.NumTicketsSold,0)
FROM T_DiscountCodes DC, T_EventRegistration ER
OUTER APPLY (SELECT COUNT(ERT1.TicketNumber) NumTimesUsed
FROM T_EventRegistrationTickets ERT1, T_EventRegistration ER1
WHERE ER1.EventRegistrationID = ERT1.EventRegistrationID
AND ER1.DiscountCode = DC.DiscountCode
AND ER1.EventID = DC.EventID
AND ER1.OrderCompleteFlag = 1) a
OUTER APPLY (SELECT COUNT(ER1.EventRegistrationID) NumTicketsSold
FROM T_EventRegistration ER1
WHERE ER1.DiscountCode = DC.DiscountCode
AND ER1.EventID = DC.EventID
AND ER1.OrderCompleteFlag = 1) a2
WHERE DC.DiscountCode *= ER.DiscountCode
AND DC.EventID = 20188
AND DC.DeleteFlag = 0
AND DC.HiddenFlag = 0
AND ER.OrderCompleteFlag = 1
ORDER BY DC.DiscountCode, NumTimesUsed