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;
select
CustomerPK,
LocalID,
ExternalID,
EarnedDate,
QtyEarned,
QtyUsed,
Value,
ServerSerial,
LastLocationID,
SVS.Description as Status,
SVS.PhraseID as StatusPhraseID,
IsNull(SUM(QtyEarned) OVER(PARTITION BY CustomerPK,LocalID,ServerSerial),0) -
IsNull(SUM(QtyUsed) OVER(PARTITION BY CustomerPK,LocalID,ServerSerial),0) 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;
select
CustomerPK,
LocalID,
ExternalID,
EarnedDate,
QtyEarned,
QtyUsed,
Value,
ServerSerial,
LastLocationID,
SVS.Description as Status,
SVS.PhraseID as StatusPhraseID,
netT.net,
AdminUserID,
ExpireDate,
PresentedCustomerID,
PresentedCardTypeID,
ResolvedCustomerID,
HHID,
Replayed,
ReplayedDate
from
SVHistory SVH with (NoLock)
inner join
StoredValueStatus SVS with (NoLock) on SVS.StatusID=SVH.StatusFlag
inner merge join
( select LocalID, ServerSerial, SUM(IsNull(QtyEarned,0)) - SUM(IsNull(QtyUsed,0)) as net
from SVHistory
where CustomerPK=18653237
group by LocalID, ServerSerial
) netT
on netT.LocalID = SVH.LocalID
and netT.ServerSerial = SVH.ServerSerial
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.