I have a SQL query which is performing badly. It is taking about 2 minutes to return the result set.
Is there a better way to rewrite the query? I know about CTE, but never used it before.
Please help.
select
CustomerPK,
LocalID,
ExternalID,
EarnedDate,
QtyEarned,
QtyUsed,
Value,
ServerSerial,
LastLocationID,
SVS.Description as Status,
SVS.PhraseID as StatusPhraseID,
(select SUM(IsNull(QtyEarned,0)) - SUM(IsNull(QtyUsed,0))
from SVHistory SVH2 with (NoLock)
where CustomerPK=18653237 and SVH2.LocalID = SVH.LocalID and SVH2.ServerSerial=SVH.ServerSerial
) as QtyAvail,
AdminUserID,
ExpireDate,
PresentedCustomerID,
PresentedCardTypeID,
ResolvedCustomerID,
HHID,
Replayed,
ReplayedDate
from
SVHistory SVH with (NoLock)
inner join
StoredValueStatus SVS with (NoLock) on SVS.StatusID=SVH.StatusFlag
where
LastLocationID <> -8
and CustomerPK = 18653237
and SVProgramID = 112
and LastUpdate between '2013-05-27 00:00:00' and '2013-06-26 23:59:59'
and Deleted = 0
order by
EarnedDate DESC,
LocalID,
ExternalID,
Status;