Stuff with xml is taking so much time in my query - sql

I have a view from the view need to fetch some result set for that purpose I have wrote following query.
So here the problem is stuff with xml is taking so much time any suggestions please.
;WITH CTE_transaction_type1 AS
(
SELECT case_summary_id,Primary_Payer, Physician,Generate_Bill,
CASE
WHEN Current_Payer IS NULL
THEN CASE
WHEN Resposible_Patient_Name IS NULL
AND PG_Patient_Name IS NULL
THEN 'PG:' + Patient_Last_Name + ',' + Patient_First_Name
WHEN Resposible_Patient_Name IS NULL
AND NULLIF(PG_Patient_Name,' ') IS NOT NULL
THEN 'SG:' + Patient_Last_Name + ',' + Patient_First_Name
ELSE Resposible_Patient_Name
END
ELSE
CASE
WHEN Current_Payer_Name IS NULL
THEN ''
ELSE Insurance_Type + Current_Payer_Name + IIF(Plan_Name IS NULL, '', ',' + Plan_Name)
END
END AS Responsible_Party_List
FROM [charts].[vw_billing_analysis]
WHERE sort_order = 0 AND transaction_type_id = 1
)
SELECT ba.Case_Summary_ID
,ba.date_of_surgery
,ba.Organization_ID
,ba.Organization_Name
,ba.Patient_Name
,ba.Patient_First_Name
,ba.Patient_Last_Name
,ba.MRN
,ba.Physician_ID
,ba.Physician
,ba.[PROCEDURE]
,ba.Current_Payer
,ba.Current_Payer_Name
,ba.Primary_Payer
,ba.Primary_Payer_ID
,ba.Insurance_Plan_ID
,ba.Insurance_Plan_Type
,ba.Plan_Name
,ba.Speciality_ID
,ba.Speciality_Name
,ba.Transaction_Responsible_Party_ID
,ba.Charge_ID
,ba.Charge_Procedure_ID
,ba.Patient_Insurance_ID
,ba.Insurance_Type
,ba.Resposible_Patient_Name
,ba.Received_From
,ba.Guarantor_Master_ID
,ba.PG_Patient_Name
,ba.Batch_Description
,ba.Period_Name
,ba.Unassigned_payment
,ba.Charge
,ba.Charge_Corr
,ba.Debit
,ba.Payments
,ba.WriteOff
,ba.Balance
,ba.Corrected_TF
,ba.Period_ID
,ba.Batch_ID
,ba.transaction_type_id
,STUFF((
SELECT '; ' + [Procedure]
FROM [charts].[vw_billing_analysis] vba
WHERE vba.case_summary_id = ba.case_summary_id
AND vba.transaction_type_id = 1
ORDER BY ba.sort_order
FOR XML PATH('')
,TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS Procedure_List
,trty1.Primary_Payer AS Primary_Payer_List
,trty1.Responsible_Party_List
,trty1.Physician AS Physician_List
,ba.Allowed_Amount
,IIF(ba.insurance_contract_id IS NULL
OR ba.Insurance_Plan_Type = 'Self-Pay', NULL, iif(ba.procedure_type IS NOT NULL, round(ba.[allowed_amount] - (ba.[allowed_amount] * ba.procedure_discount / 100.0), 3), ba.[procedure_amount])) AS [Expected_Amount]
,ba.Procedure_Amount
,ba.Generate_Bill
,trty1.Generate_Bill AS Generate_Bill_Case
,ba.Actual_Payment
,ba.First_Bill_Date
FROM [charts].[vw_billing_analysis] ba
left join cte_transaction_type1 trty1
ON ba.Case_Summary_ID=trty1.Case_Summary_ID
WHERE ba.Organization_ID =52
AND
(
(
(
(
ba.Period_Id = ('999999999')
OR '999999999' = '999999999'
)
AND 0 = 1
)
AND (
(
ba.Batch_Id IN ('999999999')
OR '999999999' = '999999999'
)
AND 0 = 1
)
)
OR (
0 = 0
AND ba.date_of_surgery >= '2018-02-01'
AND ba.date_of_surgery <= '2021-03-03'
)
)
AND (
CASE
WHEN ba.Insurance_Plan_Type IS NULL
AND ba.Insurance_Plan_ID IS NULL
AND ba.Current_Payer IS NULL
THEN '-1'
ELSE ba.Insurance_Plan_Type_Id
END IN ('999999999')
OR '999999999' = '999999999'
)
AND (
ba.Current_Payer IN ('999999999')
OR '999999999' = '999999999'
)
AND (
ba.Speciality_ID IN ('999999999')
OR '999999999' = '999999999'
)
AND (
ba.Physician_ID IN ('999999999')
OR '999999999' = '999999999'
)
AND (
isnull(ba.Primary_Payer_ID, - 1) IN ('999999999')
OR '999999999' = '999999999'
)
AND (
ba.appointment_type_id IN ('999999999')
OR '999999999' = '999999999'
)
AND (
SELECT SUM(CASE
WHEN vba.transaction_type_id = 1
THEN balance
WHEN vba.transaction_type_id = 3
THEN - balance
END)
FROM [charts].[vw_billing_analysis] vba
WHERE vba.case_summary_id = ba.case_summary_id
) >= 0
ORDER BY ba.Date_Of_Surgery DESC
,ba.MRN DESC
,ba.Patient_Name ASC
,ba.upd_tr_sort ASC
,ba.Sort_Order ASC

Related

optimize complex stored procedure

I have a very complex stored procedure and i am not that strong in SQL, please any one who has a strong SQL expertise and can help me optimize or at least can give me a hint, the procedure selects the inbox messages from database for specific user and it contains many other parameters such as paging and categories and also language input and many other details:
ALTER PROCEDURE [dbo].[Inbox]
#ConfidentialityIds NVARCHAR(100) = '0,1,2,3',
#UrgencyIds NVARCHAR(100) = '0,1,2,3',
#CorrespondenceCategoryIds NVARCHAR(100) = '1,2,3,5,6,7',
#CorrespondenceExtendedCategoryIds NVARCHAR(MAX),
#IsPrivate bit = 0,
#IsSaved bit = 0,
#Importantance VARCHAR(10) = '0, 1',
#UserId uniqueidentifier,
#SelectedPage int = 1,
#PageSize int = 25,
#Now bigint,
#IsImpersonated bit,
#ActualLoggedInUserId uniqueidentifier,
#IsEnglish bit,
#OnlyArchived bit = null,
#replaceNameWithEntName bit,
#entityIds nvarchar(MAX),
#OnlyLate bit = 0,
#Statuses NVARCHAR(100) ='1,2,3,4,5',
#ApplyPageFilter bit = 1,
#IsBundled int,
#showArchivedInCCInbox bit = 0,
#appModuleId INT = 0
WITH RECOMPILE
As
BEGIN
SET transaction isolation level read uncommitted
DECLARE #lFirstRec INT, #lLastRec INT, #lTotalRows INT
SET #lFirstRec = ( #SelectedPage - 1 ) * #PageSize
SET #lLastRec = ( #SelectedPage * #PageSize + 1 )
SET #lTotalRows = #lFirstRec - #lLastRec + 1
DECLARE #isPersonalDelegationAvailable BIT = 0
IF EXISTS(
SELECT 1
FROM DelegatedToEntityUsers d
WHERE d.DelegatedToUserId = #ActualLoggedInUserId
AND d.DelegatedFromUserId = #UserId
AND
(
d.DelegatedToEntityId IS NULL OR d.DelegationType = 1
))
BEGIN
SET #isPersonalDelegationAvailable = 1
END
DECLARE #tblEntities TABLE(Value INT)
INSERT INTO #tblEntities
SELECT Value FROM SplitCommaUniqueValues(#entityIds)
Select * from (
Select (ROW_NUMBER() OVER (ORDER BY K.ActionDate DESC, K.CorrespondenceDate DESC)) AS RowIndex,
Count(*) over () AS TotalCount,*
from (
select (ROW_NUMBER() OVER (PARTITION BY CorrespondenceID Order by CorrespondenceID DESC)) AS CorrId, *
from (
SELECT Distinct * FROM
(
SELECT
CONVERT(VARCHAR(100), R.CorrespondenceActionRecipientID) Id,
A.CorrespondenceActionID ActionId,
(CASE WHEN R.RecipientType IS NULL THEN NULL ELSE CAST(RecipientType AS INT) END) RecipientType,
A.ActionTypeId,
(CASE when #IsEnglish = 1 then ATypes.FriendlyTextEN else ATypes.FriendlyTextAR end) ActionTypeName,
A.ActionCreatedByUserID SentById,
CASE
when #replaceNameWithEntName = 0 then ISNULL(ActionCreatedByUser.ShortName, ActionCreatedByUser.EmployeeName)
when #replaceNameWithEntName = 1 and SentByEntity.EntityID not in (SELECT Value FROM #tblEntities) then case when #IsEnglish = 1 then SentByEntity.EntityNameEn else SentByEntity.EntityNameAR end
when #replaceNameWithEntName = 1 and SentByEntity.EntityID in (SELECT Value FROM #tblEntities) then ISNULL(ActionCreatedByUser.ShortName, ActionCreatedByUser.EmployeeName)
END SentByFrom,
A.WithDelegateFromUserID OnBehalfOfId,
ISNULL(WithDelegateFromUser.ShortName, WithDelegateFromUser.EmployeeName) OnBehalfOfName,
R.UserId SentToId,
CASE
when #replaceNameWithEntName = 0 then ISNULL(SentToUser.ShortName, SentToUser.EmployeeName)
when #replaceNameWithEntName = 1 and SentToEntity.EntityID not in (SELECT Value FROM #tblEntities) then case when #IsEnglish = 1 then SentToEntity.EntityNameEn else SentToEntity.EntityNameAR end
when #replaceNameWithEntName = 1 and SentToEntity.EntityID in (SELECT Value FROM #tblEntities) then isnull(ISNULL(SentToUser.ShortName, SentToUser.EmployeeName), case when #IsEnglish = 1 then SentToEntity.EntityNameEn else SentToEntity.EntityNameAR end)
END SentToName,
R.EntityID SentToEntityId,
SentToEntity.EntityNameAR SentToEntityNameAR,
SentToEntity.EntityNameEN SentToEntityNameEN,
R.Seen,
(CASE WHEN MR.CorrespondenceActionRecipientID IS NOT NULL THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END) IsReadByUser,
CAST(ISNULL(FollowedByUser.IsFollowedByUser, 0) AS BIT) IsFollowedByUser,
(
CASE WHEN EXISTS(SELECT 1 FROM CorrespondenceFollowups
WHERE CorrespondenceID = C.CorrespondenceID
AND UserId = #UserId AND AssignedByUserId IS NOT NULL) THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END
) IsAssignedFollowToUser,
(
CASE WHEN EXISTS(SELECT 1 FROM CorrespondenceFollowups
WHERE CorrespondenceID = C.CorrespondenceID
AND AssignedByUserId = #UserId) THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END
) IsAssignedFollowByUser,
A.CorrespondenceID,
A.ActionDate,
A.ActionDeadlineDate,
C.CompletionDate,
C.CorrespondenceDeadlineDate CorrDeadlineDate,
C.OwnerUserID CorrOwnerId,
C.ChildNo ChildNo,
OwnerUser.EmployeeName CorrOwnerName,
C.Important,
C.UrgencyId,
C.LetterCorrespondenceId,
(CASE when #IsEnglish = 1 then U.TextEN else U.TextAR end) UrgencyText,
C.ConfidentialityId,
(CASE when #IsEnglish = 1 then Confid.TextEN else Confid.TextAR end) ConfidentialityText,
C.CorrespondenceCategoryId CategoryId,
C.CorrespondenceClassificationID CorrespondenceClassificationID,
(CASE when #IsEnglish = 1 then CCat.TextEN else CCat.TextAR end) CategoryName,
CCat.ColorClass ColorClass,
C.Subject,
c.CorrespondenceFormula,
C.InternalSenderEntityId,
C.InternalRecipientEntityId,
C.[Sequence] [Sequence],
C.Year,
C.CompletionStatus Status,
Null Number,
(CASE WHEN (
(
(A.ActionDeadlineDate IS NOT NULL AND A.ActionDeadlineDate < #Now)
OR
(C.CorrespondenceDeadlineDate IS NOT NULL AND C.CorrespondenceDeadlineDate < #Now)
)
AND
C.[Closed-Archived] = 0) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END) IsLate,
CAST(0 AS BIT) HasAnyEvents,
C.CreatedByUserId,
CreatedByUser.EmployeeName CreatedByUserName,
CAST(C.CorrespondenceDate AS VARCHAR(50)) CorrDate,
C.CorrespondenceDate,
C.[Closed-Archived] ClosedArchived,
C.IsSaved SavedActionTaken,
((CASE WHEN C.Important = 1 THEN CASE WHEN #IsEnglish = 1 THEN N'Important' ELSE N'هامة' END ELSE '' END) + (CASE WHEN C.Important = 1 AND C.UrgencyID <> 0 THEN CASE WHEN #IsEnglish = 1 THEN N' and ' ELSE N' و ' END ELSE '' END) + (CASE WHEN C.UrgencyID <> 0 THEN (CASE when #IsEnglish = 1 then U.TextEN else U.TextAR end) ELSE '' END)) ImportantUrgencyText,
CAST(C.IsAutoSaved AS BIT) IsAutoSaved,
-- *******************************************************************
rem.ReminderDate as CorrespondenceReminderDateTime,
remAction.ReminderDate as ActionReminderDateTime
FROM (
SELECT * FROM Correspondences CC
WHERE CC.IsDeleted = 0
AND CC.LetterCorrespondenceId IS NULL
AND (CC.ConfidentialityId IN (SELECT [Value] FROM SplitCommaUniqueValues(#ConfidentialityIds)))
AND
( #IsPrivate = 0 OR
(
#IsPrivate = 1 AND CC.IsForPresident = 1
)
)
AND
(
(CC.IsSaved = case when #IsSaved =1 then 1 else CC.IsSaved end)
)
AND (#appModuleId = 0 OR CC.AppModuleId = #appModuleId)
AND (CC.UrgencyID IN (SELECT value FROM SplitCommaUniqueValues(#UrgencyIds)))
AND (CC.Important IN (SELECT value FROM SplitCommaUniqueValues(#Importantance)))
AND CC.CompletionStatus IN(SELECT value FROM SplitComma(#Statuses))
) C
LEFT JOIN CorrespondenceExtendedDetails CorrExt
ON CorrExt.CorrespondenceID = C.CorrespondenceID
LEFT JOIN CorrespondenceActions A
ON C.CorrespondenceID = A.CorrespondenceID
AND A.IsDeleted = 0
AND A.ActionTypeID != 7 -- إنهاء التذكير
LEFT JOIN CorrespondenceActionRecipients R
ON A.CorrespondenceActionID = R.CorrespondenceActionID
AND (
R.AsCopy = 1
)
JOIN Urgencies U
ON C.UrgencyID = U.ID
JOIN ActionTypes ATypes
ON A.ActionTypeID = ATypes.ID
JOIN CorrespondenceCategories CCat
ON C.CorrespondenceCategoryId = CCat.ID
JOIN Confidentialities Confid
ON C.ConfidentialityID = Confid.ID
LEFT JOIN Users ActionCreatedByUser
ON A.ActionCreatedByUserID = ActionCreatedByUser.UserId
LEFT JOIN Users WithDelegateFromUser
ON A.WithDelegateFromUserID = WithDelegateFromUser.UserID
LEFT JOIN Entities SentByEntity
ON A.ActionCreatedByUserEntityId = SentByEntity.EntityID
LEFT JOIN Users SentToUser
ON R.UserId = SentToUser.UserId
LEFT JOIN Entities SentToEntity
ON R.EntityID = SentToEntity.EntityID
LEFT JOIN Users OwnerUser
ON C.OwnerUserID = OwnerUser.UserId
LEFT JOIN Users CreatedByUser
ON C.CreatedByUserID = CreatedByUser.UserId
LEFT JOIN MarkAsReads MR
ON R.CorrespondenceActionRecipientID = MR.CorrespondenceActionRecipientID
AND MR.UserId = #UserId
OUTER APPLY
(
SELECT TOP 1 1 IsFollowedByUser
FROM CorrespondenceFollowups CF
WHERE CF.CorrespondenceId = C.CorrespondenceID
AND CF.UserId = #UserId
AND CF.AssignedByUserId IS NULL
) FollowedByUser
-- *******************************************************************
LEFT JOIN LinkedCorrespondenceSchedules CS on CS.CorrespondenceID = C.CorrespondenceID
LEFT JOIN Reminder rem on rem.ReferenceId=C.CorrespondenceID AND rem.ReferenceType = 1 AND rem.CreatedByUserId=#UserId AND (rem.[Status] = 1 OR rem.[Status] = 2)
Left JOIN Reminder remAction on remAction.ReferenceId = A.CorrespondenceActionID AND remAction.ReferenceType = 2 AND remAction.CreatedByUserId=#UserId AND (remAction.[Status] = 1 OR remAction.[Status] = 2)
-- *******************************************************************
WHERE (
(C.CorrespondenceCategoryId IN (SELECT Value FROM SplitComma(#CorrespondenceCategoryIds)) AND CorrExt.CorrespondenceExtendedCategoryId IS NULL)
OR (CorrExt.CorrespondenceExtendedCategoryId IN (SELECT Value FROM SplitComma(#CorrespondenceExtendedCategoryIds)))
)
AND
(
-- Personal
(
(
(#IsImpersonated = 0 AND R.UserId = #UserId)
OR
(#IsImpersonated = 1 AND R.UserId = #UserId AND #isPersonalDelegationAvailable = 1)
)
AND R.RecipientType = 1 AND R.UserId Is Not null
)
OR
-- Me as Manager (Impersonation mode handled from code by sending the proper Entity Ids.
(
(R.EntityID IN (SELECT Value FROM #tblEntities) AND R.EntityID Is Not null AND R.RecipientType != 1)
)
)
AND C.[Closed-Archived] = Case When #showArchivedInCCInbox = 1 Then 0 Else C.[Closed-Archived] End
AND R.UserTokeAction = 0
AND NOT EXISTS (
SELECT 1 FROM Correspondences CC
INNER JOIN CorrespondenceLinks CL
ON CC.CorrespondenceID = CL.LinkedCorrespondenceID AND CC.CorrespondenceID = C.CorrespondenceID AND CL.LinkTypeID = #IsBundled
)
) T
WHERE T.LetterCorrespondenceId is null
) as ttt
) K where CorrId = 1
)N where (#ApplyPageFilter = 0 OR ( RowIndex > #lFirstRec AND RowIndex < #lLastRec))
Order by
ActionDate DESC, CorrespondenceDate
option(recompile)
END

Is it possible to Pivot this query?

My query
SELECT DISTINCT dbo.tblacc_cv.cv_docno,
dbo.tblacc_cv.cv_docdate,
dbo.tblacc_cv.cv_suppliername,
dbo.tblacc_cv.cv_extdocno,
dbo.tblacc_chartaccount.coa_cvtype AS cvtype,
dbo.tblacc_glentry.gl_accountid,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid = '201001' THEN Sum(
dbo.tblacc_glentry.gl_credit)
ELSE NULL
END ) AS AP,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid = '208000' THEN Sum(
dbo.tblacc_glentry.gl_amount)
ELSE NULL
END ) AS EWT,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid = '616000'
AND dbo.tblacc_chartaccount.coa_cvtype = 'S' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS FABpur,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid = '603000'
AND dbo.tblacc_chartaccount.coa_cvtype = 'S' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS FABcre,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid = '602000'
AND dbo.tblacc_chartaccount.coa_cvtype = 'S' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS RawMat,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid = '601003'
AND dbo.tblacc_chartaccount.coa_cvtype = 'S' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS PurCre,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid NOT IN (
'201001', '208000', '616000', '603000',
'602000', '601003' ) THEN
dbo.tblacc_glentry.gl_accountname
ELSE NULL
END ) AS GL_AccountName,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid NOT IN (
'616000', '603000', '602000', '601003'
)
AND dbo.tblacc_chartaccount.coa_cvtype = 'M' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS MOdr,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid NOT IN (
'616000', '603000', '602000', '601003'
)
AND dbo.tblacc_chartaccount.coa_cvtype = 'F' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS FDR,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid NOT IN (
'201001', '208000', '616000', '603000',
'602000', '601003' )
AND dbo.tblacc_chartaccount.coa_cvtype = 'S' THEN Sum(
dbo.tblacc_glentry.gl_debit)
ELSE NULL
END ) AS SunDR,
( CASE
WHEN dbo.tblacc_glentry.gl_accountid NOT IN (
'201001', '208000', '616000', '603000',
'602000', '601003' )
AND dbo.tblacc_chartaccount.coa_cvtype = 'S' THEN Sum(
dbo.tblacc_glentry.gl_credit)
ELSE NULL
END ) AS SunCR
FROM dbo.tblacc_glentry
INNER JOIN dbo.tblacc_apv
ON dbo.tblacc_glentry.gl_docno = dbo.tblacc_apv.apv_docno
INNER JOIN dbo.tblacc_cv
INNER JOIN dbo.tblacc_cvdetail
ON dbo.tblacc_cv.cv_docno =
dbo.tblacc_cvdetail.cvd_cv_docno
ON dbo.tblacc_apv.apv_docno = dbo.tblacc_cvdetail.cvd_refdocno
INNER JOIN dbo.tblacc_chartaccount
ON dbo.tblacc_glentry.gl_accountid =
dbo.tblacc_chartaccount.coa_account_id
WHERE ( dbo.tblacc_cv.cv_docdate BETWEEN
'01/01/2018 00:00:00' AND '1/30/2018 23:59:59' )
GROUP BY dbo.tblacc_cv.cv_docno,
dbo.tblacc_cv.cv_docdate,
dbo.tblacc_cv.cv_suppliername,
dbo.tblacc_glentry.gl_accountname,
dbo.tblacc_cv.cv_extdocno,
dbo.tblacc_chartaccount.coa_cvtype,
dbo.tblacc_glentry.gl_accountid,
dbo.tblacc_glentry.gl_credit,
dbo.tblacc_glentry.gl_amount,
dbo.tblacc_glentry.gl_debit
ORDER BY dbo.tblacc_cv.cv_docdate ASC
Sample Output
Desired Ouput
Your desired output is not an example of a PIVOT.
Lacking a detailed explanation of your logic, I can tell you that you can get your desired output by GROUPing BY the first four columns, and applying MAX() to all the others. (Except cvtype which would be a MIN).

ERROR ORA-00905: missing keyword (microsoft ole db provider for oracle)

can anyone see what keyword is missing from the pl/sql query below?
I am getting the error ORA-00905: missing keyword (microsoft ole db provider for oracle)
not sure what keyword is missing - this is an odbc query to oracle database
SELECT "STAT"."ORD"."SAMPLEID",
MAX(CASE WHEN "STAT"."ORDANAEL"."MC"='QAERS' THEN N"STAT"."ORDANAEL"."RES_TXT" ELSE
'' END) AS ERSID,
"STAT"."ORDMCSTP_V"."SEQNB", "STAT"."ORD"."ORDPATNAME",
"STAT"."ORD"."ORDPATBIRTHDT", "STAT"."ORD"."CORORDNB", "STAT"."ORD"."PROJNB",
Max(CASE WHEN "STAT"."ORDANAEL"."MC"='AMMOL' THEN 'AMMOL'
WHEN "STAT"."ORDANAEL"."MC"='AMMOLR' THEN 'AMMOLR' ELSE '' END) AS TEST,
Max(CASE WHEN "STAT"."ORDANAEL"."MC"='AMMOL' THEN N"STAT"."ORDRESMCEL"."MC_RES"
WHEN "STAT"."ORDANAEL"."MC"='AMMOLR' THEN N"STAT"."ORDRESMCEL"."MC_RES" ELSE ''
END) AS MC_RES,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMIMI' THEN N"STAT"."ORDMCSTPEL"."RES"
ELSE '' END) AS IMI,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMIMP' THEN N"STAT"."ORDMCSTPEL"."RES"
ELSE '' END) AS IMP,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMNDM' THEN N "STAT"."ORDMCSTPEL"."RES"
ELSE '' END) AS NDM,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMOX48' THEN
N "STAT"."ORDMCSTPEL"."RES" ELSE '' END) AS OXA48,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMSPM' THEN N "STAT"."ORDMCSTPEL"."RES"
ELSE '' END) AS SPM,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMVIM' THEN N "STAT"."ORDMCSTPEL"."RES"
ELSE '' END) AS VIM,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMDIM' THEN N "STAT"."ORDMCSTPEL"."RES"
ELSE '' END) AS DIM,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMKPC' THEN N "STAT"."ORDMCSTPEL"."RES"
ELSE '' END) AS KPC,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMGES' THEN N "STAT"."ORDMCSTPEL"."RES"
ELSE '' END) AS GES,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMSME' THEN N "STAT"."ORDMCSTPEL"."RES"
ELSE '' END) AS SME,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMFRI1' THEN
N "STAT"."ORDMCSTPEL"."RES" ELSE '' END) AS FRI1,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMSIM' THEN N "STAT"."ORDMCSTPEL"."RES"
ELSE '' END) AS SIM,
Max( CASE WHEN "STAT"."ORDMCSTP_V"."STEPMC"='AMGIM' THEN N "STAT"."ORDMCSTPEL"."RES"
ELSE '' END) AS GIM,
Max( CASE WHEN "STAT"."ORDANAEL"."MC"='AMMOL' THEN N "STAT"."ORDANAEL"."VALMED" ELSE
'' END) AS VALMED_AMMOL,
Max( CASE WHEN "STAT"."ORDANAEL"."MC"='AMMOL' AND
"STAT"."ORDANAEL_D"."DFIELD"='RR' THEN N "STAT"."ORDANAEL_D"."DVALUE" ELSE '' END)
AS RPT_DT_AMMOL,
"STAT"."ORDANAEL"."RES_ST"
FROM (("STAT"."ORDMCSTPEL" INNER JOIN ("STAT"."ORDMCSTP_V" INNER JOIN
("STAT"."ORD" INNER JOIN "STAT"."ORDANAEL" ON ("STAT"."ORD"."LID" =
"STAT"."ORDANAEL"."LID") AND ("STAT"."ORD"."LPERIOD" =
"STAT"."ORDANAEL"."LPERIOD") AND ("STAT"."ORD"."ORDNB" =
"STAT"."ORDANAEL"."ORDNB")) ON ("STAT"."ORDMCSTP_V"."LID" = "STAT"."ORD"."LID")
AND ("STAT"."ORDMCSTP_V"."LPERIOD" = "STAT"."ORD"."LPERIOD") AND
("STAT"."ORDMCSTP_V"."ORDNB" = "STAT"."ORD"."ORDNB")) ON ("STAT"."ORDMCSTPEL"."BC"
= "STAT"."ORDMCSTP_V"."BC") AND ("STAT"."ORDMCSTPEL"."CURRENT_STEPNB" =
"STAT"."ORDMCSTP_V"."CURRENT_STEPNB")) INNER JOIN "STAT"."ORDANAEL_D" ON
("STAT"."ORDANAEL"."NBINT" = "STAT"."ORDANAEL_D"."DNBINT") AND
("STAT"."ORDANAEL"."SPSEQ" = "STAT"."ORDANAEL_D"."DSPSEQ") AND
("STAT"."ORDANAEL"."ORDNB" = "STAT"."ORDANAEL_D"."DORDNB") AND
("STAT"."ORDANAEL"."LPERIOD" = "STAT"."ORDANAEL_D"."DLPERIOD") AND
("STAT"."ORDANAEL"."LID" = "STAT"."ORDANAEL_D"."DLID")) INNER JOIN
"STAT"."ORDRESMCEL" ON ("STAT"."ORDMCSTP_V"."SEQNB" = "STAT"."ORDRESMCEL"."SEQNB")
AND ("STAT"."ORDANAEL"."ORDNB" = "STAT"."ORDRESMCEL"."ORDNB") AND
("STAT"."ORDANAEL"."LPERIOD" = "STAT"."ORDRESMCEL"."LPERIOD") AND
("STAT"."ORDANAEL"."LID" = "STAT"."ORDRESMCEL"."LID")
WHERE (("STAT"."ORD"."LID")='H1')
AND (("STAT"."ORD"."LPERIOD")>'5200')
AND (("STAT"."ORD"."PROJNB")='ACPOERS')
GROUP BY "STAT"."ORD"."SAMPLEID", "STAT"."ORDMCSTP_V"."SEQNB",
"STAT"."ORD"."ORDPATNAME", "STAT"."ORD"."ORDPATBIRTHDT", "STAT"."ORD"."CORORDNB",
"STAT"."ORD"."PROJNB", "STAT"."ORDANAEL"."RES_ST"
HAVING ((("STAT"."ORDMCSTP_V"."SEQNB") Is Not Null) AND (("STAT"."ORD"."PROJNB")
='ACPOERS') AND (("STAT"."ORDANAEL"."RES_ST")>'4'))
Just too big for comment. Just cleaned up the double quotes and the N and it comes clean in a SQL formatter.
SELECT STAT.ORD.SAMPLEID,
MAX ( CASE WHEN STAT.ORDANAEL.MC = 'QAERS' THEN STAT.ORDANAEL.RES_TXT ELSE '' END ) AS ersid,
STAT.ORDMCSTP_V.SEQNB,
STAT.ORD.ORDPATNAME,
STAT.ORD.ORDPATBIRTHDT,
STAT.ORD.CORORDNB,
STAT.ORD.PROJNB,
MAX (
CASE
WHEN STAT.ORDANAEL.MC = 'AMMOL' THEN 'AMMOL'
WHEN STAT.ORDANAEL.MC = 'AMMOLR' THEN 'AMMOLR'
ELSE ''
END )
AS test,
MAX (
CASE
WHEN STAT.ORDANAEL.MC = 'AMMOL' THEN STAT.ORDRESMCEL.MC_RES
WHEN STAT.ORDANAEL.MC = 'AMMOLR' THEN STAT.ORDRESMCEL.MC_RES
ELSE ''
END )
AS mc_res,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMIMI' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS imi,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMIMP' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS imp,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMNDM' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS ndm,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMOX48' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS oxa48,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMSPM' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS spm,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMVIM' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS vim,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMDIM' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS dim,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMKPC' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS kpc,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMGES' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS ges,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMSME' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS sme,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMFRI1' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS fri1,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMSIM' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS sim,
MAX ( CASE WHEN STAT.ORDMCSTP_V.STEPMC = 'AMGIM' THEN STAT.ORDMCSTPEL.RES ELSE '' END ) AS gim,
MAX ( CASE WHEN STAT.ORDANAEL.MC = 'AMMOL' THEN STAT.ORDANAEL.VALMED ELSE '' END )
AS valmed_ammol,
MAX ( CASE
WHEN STAT.ORDANAEL.MC = 'AMMOL'
AND STAT.ORDANAEL_D.DFIELD = 'RR' THEN
STAT.ORDANAEL_D.DVALUE
ELSE
''
END )
AS rpt_dt_ammol,
STAT.ORDANAEL.RES_ST
FROM ((STAT.ORDMCSTPEL
INNER JOIN (STAT.ORDMCSTP_V
INNER JOIN (STAT.ORD
INNER JOIN STAT.ORDANAEL
ON ( STAT.ORD.LID = STAT.ORDANAEL.LID )
AND ( STAT.ORD.LPERIOD = STAT.ORDANAEL.LPERIOD )
AND ( STAT.ORD.ORDNB = STAT.ORDANAEL.ORDNB ))
ON ( STAT.ORDMCSTP_V.LID = STAT.ORD.LID )
AND ( STAT.ORDMCSTP_V.LPERIOD = STAT.ORD.LPERIOD )
AND ( STAT.ORDMCSTP_V.ORDNB = STAT.ORD.ORDNB ))
ON ( STAT.ORDMCSTPEL.BC = STAT.ORDMCSTP_V.BC )
AND ( STAT.ORDMCSTPEL.CURRENT_STEPNB = STAT.ORDMCSTP_V.CURRENT_STEPNB ))
INNER JOIN STAT.ORDANAEL_D
ON ( STAT.ORDANAEL.NBINT = STAT.ORDANAEL_D.DNBINT )
AND ( STAT.ORDANAEL.SPSEQ = STAT.ORDANAEL_D.DSPSEQ )
AND ( STAT.ORDANAEL.ORDNB = STAT.ORDANAEL_D.DORDNB )
AND ( STAT.ORDANAEL.LPERIOD = STAT.ORDANAEL_D.DLPERIOD )
AND ( STAT.ORDANAEL.LID = STAT.ORDANAEL_D.DLID ))
INNER JOIN STAT.ORDRESMCEL
ON ( STAT.ORDMCSTP_V.SEQNB = STAT.ORDRESMCEL.SEQNB )
AND ( STAT.ORDANAEL.ORDNB = STAT.ORDRESMCEL.ORDNB )
AND ( STAT.ORDANAEL.LPERIOD = STAT.ORDRESMCEL.LPERIOD )
AND ( STAT.ORDANAEL.LID = STAT.ORDRESMCEL.LID )
WHERE ( ( STAT.ORD.LID ) = 'H1' )
AND ( ( STAT.ORD.LPERIOD ) > '5200' )
AND ( ( STAT.ORD.PROJNB ) = 'ACPOERS' )
GROUP BY STAT.ORD.SAMPLEID,
STAT.ORDMCSTP_V.SEQNB,
STAT.ORD.ORDPATNAME,
STAT.ORD.ORDPATBIRTHDT,
STAT.ORD.CORORDNB,
STAT.ORD.PROJNB,
STAT.ORDANAEL.RES_ST
HAVING ( ( ( STAT.ORDMCSTP_V.SEQNB ) IS NOT NULL )
AND ( ( STAT.ORD.PROJNB ) = 'ACPOERS' )
AND ( ( STAT.ORDANAEL.RES_ST ) > '4' ) );
You can use N in front of a string literal to mark it as an nvarchar2. Example:
select N'abc' from dual
But you can't use it in front of an identifier the way you are doing it. If you want to read a certain column value as an nvarchar2, you'll need to cast it as such. Example:
... THEN cast("STAT"."ORDANAEL"."RES_TXT" as nvarchar2(50)) ...

Make sql query run faster

Is it possible to make some optimization on such query ?
with t (CurrentPrice, [Weight])
as ( select CurrentPrice, [Weight] from SomeTable where GroupingId = SomeBigIntId )
SELECT MaxExactPrice = ( select MAX(CurrentPrice) FROM t Where [Weight] > 0 ),
MinExactPrice = ( select MIN(CurrentPrice) FROM t Where [Weight] > 0 ),
MaxSimilarPrice = ( select MAX(CurrentPrice) FROM t Where [Weight] = 0 ),
MinSimilarPrice = ( select MIN(CurrentPrice) FROM t Where [Weight] = 0 ),
ExactCount = ( select Count(*) FROM t Where [Weight] > 0 ),
SimilarCount = ( select Count(*) FROM t Where [Weight] = 0 ),
Count(*) as TotalCount
FROM t
Thank you.
Do this instead. this way you do not have to hit same table 8 different times.
select MAX(CASE WHEN [Weight] > 0 THEN CurrentPrice ELSE NULL END) AS MaxExactPrice
,MIN(CASE WHEN [Weight] > 0 THEN CurrentPrice ELSE NULL END) AS MinExactPrice
,MAX(CASE WHEN [Weight] = 0 THEN CurrentPrice ELSE NULL END) AS MaxSimilarPrice
,MIN(CASE WHEN [Weight] = 0 THEN CurrentPrice ELSE NULL END) AS MinSimilarPrice
,COUNT(CASE WHEN [Weight] > 0 THEN 1 ELSE NULL END ) AS ExactCount
,COUNT(CASE WHEN [Weight] = 0 THEN 1 ELSE NULL END ) AS SimilarCount
,COUNT(*)AS TotalCount
from SomeTable where GroupingId = SomeBigIntId

Query Runs Slower The Second Time

I have this massive query that I can typically run in under 2 minutes. However, when I run it a second time about a minute after, it goes on infinitely... so I kill the process and my SSMS session. I don't have any other jobs running in the background.
Is something else being retained on the server? I think I'm missing something as far as how SQL Server works.
Thanks.
EDIT: Here's the SQL (had to do a little obfuscation)
SELECT pl.OrangeLocationID ,
e.EventID ,
cr.Title AS [Event Type] ,
su.LastName + ', ' + su.FirstName AS FMR ,
CONVERT(VARCHAR(20), pl.Report_Date, 101) AS [Report Entry Date] ,
l.Name ,
l.Number ,
ll.SodaPopLocationID AS [SodaPop Location ID] ,
l.Zip ,
c.Channel ,
pl.DT AS [ReportedDate] ,
RIGHT(pl.DT_start, 8) AS [ReportedStartTime] ,
RIGHT(pl.DT_end, 8) AS [ReportedEndTime] ,
[CMS].dbo.dDateDiff(pl.DT_start, pl.DT_end) AS [ReportedDuration] ,
pl.scheduled_date AS [ScheduledDate] ,
RIGHT(pl.scheduled_start, 8) AS [ScheduledStartTime] ,
RIGHT(pl.scheduled_end, 8) AS [ScheduledEndTime] ,
[CMS].dbo.dDateDiff(pl.scheduled_start, pl.DT_end) AS [ScheduledDuration] ,
e.HoursPaid AS [Rep Hours Worked] ,
ISNULL(PP.[RepCount], 0) AS [RepCount] ,
CASE WHEN [CMS].dbo.dDateDiff(pl.DT_start, pl.DT_end) = ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
THEN [CMS].dbo.oa_HourDateDiff(pl.DT_start, pl.DT_end)
WHEN [CMS].dbo.dDateDiff(pl.scheduled_start, pl.DT_end) = ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
THEN [CMS].dbo.oa_HourDateDiff(pl.scheduled_start, pl.DT_end)
ELSE ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
END AS [FinalDuration] ,
g.[Description] AS [OA Market] ,
g.SodaPop_Region AS [SodaPop Region] ,
g.SodaPop_Area AS [SodaPop Area] ,
coup4 ,
coupo ,
coupo_e ,
card_num ,
promo ,
promo_no ,
promo_no_o ,
highlight1 ,
highlight2 ,
highlight3 ,
mgmt_reaction ,
mgmt_reaction_e ,
comm_p ,
comm_n ,
r.comments ,
s_fname ,
s_lname ,
v_title ,
ll.KeyAccountCorp AS [Key Account Corp.] ,
interact_new + interact_rep AS [interact_total] ,
samp_new + samp_rep AS [samp_total] ,
purch_new + purch_rep AS [purch_total] ,
23 / ( NULLIF(( interact_new + interact_rep ), 0) * 1.0 ) AS [Int_Crate] ,
CASE WHEN sampletype = 11 THEN ( purch_new + purch_rep ) / ( NULLIF(( samp_new + samp_rep ), 0) * 1.0 )
ELSE NULL
END AS [Samp_Crate] ,
coup1 + coup2 AS [coup_total] ,
CASE WHEN coup1 + coupo > 0 THEN 1
ELSE 0
END AS [CoupDist] ,
DATEPART(month, pl.DT) AS [Visit_Month] ,
DATEPART(quarter, pl.DT) AS [Quarter] ,
DATEPART(weekday, pl.DT) AS [Weekday] ,
CASE DATEPART(weekday, pl.DT)
WHEN 6 THEN 'Fri'
WHEN 7 THEN 'Sat'
WHEN 1 THEN 'Sun'
ELSE 'Mon-Thurs'
END AS [Weekday_Grouped] ,
CASE WHEN dbo.Exception(pl.OrangeLocationID, 12) = 1
OR dbo.Exception(pl.OrangeLocationID, 13) = 1
OR dbo.Exception(pl.OrangeLocationID, 14) = 1 THEN 1
ELSE 0
END AS [EVolume] ,
CASE WHEN dbo.DoesHaveException(pl.OrangeLocationID, 18) = 1 THEN 1
ELSE 0
END AS [CVolume] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 9) = 1
OR dbo.eException(pl.OrangeLocationID, 22) = 1 THEN 1
ELSE 0
END AS [Volumes] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 8) = 1
OR dbo.eException(pl.OrangeLocationID, 21) = 1 THEN 1
ELSE 0
END AS [Sales Price] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 11) = 1 THEN 1
ELSE 0
END AS [Sample Volume] ,
ISNULL(i.[NormalizedSold], 0) AS [EQBottlesSold] ,
CASE WHEN ISNULL(purch_new, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END AS [EQBottlesSoldPerPurch] ,
ac.AvgSales ,
ac.STDEVSales ,
( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales AS [sl] ,
ac.AvgPurchasers ,
ac.STDEVPurchasers ,
( ISNULL(r.purch_new, 0) - ac.AvgPurchasers ) / ac.STrchasers AS [ZScore_Purchasers] ,
ac.AvgConversions ,
ac.STDEVConversions ,
( ISNULL(( purch_new + purch_rep ) / ( NULLIF(( interact_new ), 0) ), 0) - ac.AvgConversions )
/ ac.STDEVConversions AS [ZScore_Conversions] ,
ac.[AvgSalesPerPurchaser] ,
ac.[STDEVSalesPerPurchaser] ,
( ISNULL(( CASE WHEN ISNULL(purch_new, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END ), 0) - ac.[AvgSalesPerPurchaser] ) / ac.[STDEVSalesPerPurchaser] AS [SalesPerPurchaser] ,
( ( ( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales )
+ ( (ISNULL(( CASE WHEN ISNULL(purch_new + purch_rep, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END ), 0) - ac.[AvgSalesPerPurchaser]) ) ) / 4 AS [core] ,
( ( (( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales) ) / 4 ) + 3 AS [core] ,
su.aaUserID ,
l.LsocationID
FROM [CMS_SodaPop].dbo.Schedule pl WITH ( NOLOCK )
INNER JOIN [CMS_SodaPop].dbo.Report r WITH ( NOLOCK ) ON r.OrangeLocationID = pl.OrangeLocationID
INNER JOIN [CMS].dbo.Users su WITH ( NOLOCK ) ON su.UserID = pl.Rep_FMR
INNER JOIN [CMS].dbo.Locations l WITH ( NOLOCK ) ON l.LocationID = pl.LocationID
INNER JOIN [CMS].dbo.OrangeReports cr WITH ( NOLOCK ) ON cr.RedID = pl.RedID
INNER JOIN [CMS_SodaPop].dbo.Events e WITH ( NOLOCK ) ON e.OrangeLocationID = pl.OrangeLocationID
INNER JOIN [CMS_SodaPop].dbo.MarketList g WITH ( NOLOCK ) ON g.GroupID = pl.GroupID
INNER JOIN [CMS_SodaPop].dbo.Locations ll WITH ( NOLOCK ) ON ll.LocationID = pl.LocationID
LEFT JOIN [CMS_SodaPop].dbo.Channels c WITH ( NOLOCK ) ON ll.ChannelID = c.ChannelID
LEFT JOIN ( SELECT PLocationID ,
COUNT(DISTINCT UserID) AS [RepCount]
FROM [CMS_roll].dbo.rollItems WITH ( NOLOCK )
WHERE RedID = 154
GROUP BY OrangeLocationID
) PP ON PP.OrangeLocationID = pl.OrangeLocationID
LEFT JOIN ( SELECT OrangeLocationID ,
SUM(NormalizedSold) AS [NormalizedSold]
FROM [Analysis].dbo.[vSodaPop_Retail_Inventory] WITH ( NOLOCK )
GROUP BY OrangeLocationID
) i ON i.OrangeLocationID = pl.OrangeLocationID
LEFT JOIN [Analysis].dbo.[vSodaPop_Calculations] ac WITH ( NOLOCK ) ON ac.[Quarter] = CASE WHEN DATEPART(MM,
[DT]) IN ( 10,
11, 12 ) THEN 4
END
AND ac.[Year] = DATEPART(YY, pl.DT)
WHERE pl.Activity = 1
AND pl.RedID = 154
AND pl.GroupID <> 444
AND pl.[DT] < GETDATE()
AND DATEPART(YY, [DT]) >= 2010
AND ISNULL(i.NormalizedSold, 0) >= 0
AND DATEPART(year, GETDATE()) = DATEPART(year, r.Insert_Date)
Would have to see the query to really dig in however..
you could try adding OPTION (RECOMPILE) to the end of the query to force it to create a new execution plan.
Are you using Temp Tables?
Cursors not deallocated & closed?
You can look at Profiler to see if anything looks different between the 2 executions.
Are you sure it isn't being blocked by another process the second time?
What happens if you execute
CHECKPOINT;
GO;
DBCC DROPCLEANBUFFERS;
GO;
DBCC FREEPROCCACHE;
GO;
between the queries? This is not really a solution but will help diagnosis.