SQL Query Optimization with Union Select - sql

I have this query, it returns 570 rows, but runs 2m 35s. In SQL the query execute, but in my solution, it gives a timeout. How can I optimize this to run under 1m, pref 30s.
SELECT [Region] = Region.FirstName,
[Patient] = Patient.Name,
[PatientStatus] = AccountRating.Name,
[MedicalAid] = AccountType.Name,
[QuoteAmount] = ( SELECT TOP 1 A.Response
FROM dbo.Questionnaire Q
JOIN dbo.QuestionnaireDefinition QRD
ON QRD.QuestionnaireDefinitionID = Q.QuestionnaireDefinitionID
AND QRD.Name = 'Internal Admin'
LEFT JOIN QuestionDefinition QD
ON Q.QuestionnaireDefinitionID = QD.QuestionnaireDefinitionID
AND QD.QuestionDefinitionID = 5966
LEFT OUTER JOIN Answer A
ON A.QuestionnaireID = Q.QuestionnaireID
AND A.QuestionDefinitionID = QD.QuestionDefinitionID
WHERE Q.IsActive = 1
AND Q.SubscriberID = 240
AND Q.AccountID = Patient.AccountID
),
[InvoiceAmount] = ( SELECT TOP 1 A.Response
FROM dbo.Questionnaire Q
JOIN dbo.QuestionnaireDefinition QRD
ON QRD.QuestionnaireDefinitionID = Q.QuestionnaireDefinitionID
AND QRD.Name = 'Internal Admin'
LEFT JOIN QuestionDefinition QD
ON Q.QuestionnaireDefinitionID = QD.QuestionnaireDefinitionID
AND QD.QuestionDefinitionID = 5969
LEFT OUTER JOIN Answer A
ON A.QuestionnaireID = Q.QuestionnaireID
AND A.QuestionDefinitionID = QD.QuestionDefinitionID
WHERE Q.IsActive = 1
AND Q.SubscriberID = 240
AND Q.AccountID = Patient.AccountID
),
[DateSubmitted] = ( SELECT TOP 1 A.Response
FROM dbo.Questionnaire Q
JOIN dbo.QuestionnaireDefinition QRD
ON QRD.QuestionnaireDefinitionID = Q.QuestionnaireDefinitionID
AND QRD.Name = 'Internal Admin'
LEFT JOIN QuestionDefinition QD
ON Q.QuestionnaireDefinitionID = QD.QuestionnaireDefinitionID
AND QD.QuestionDefinitionID = 5965
LEFT OUTER JOIN Answer A
ON A.QuestionnaireID = Q.QuestionnaireID
AND A.QuestionDefinitionID = QD.QuestionDefinitionID
WHERE Q.IsActive = 1
AND Q.SubscriberID = 240
AND Q.AccountID = Patient.AccountID
),
[DateApprovedDeclined] = ( SELECT TOP 1 A.Response
FROM dbo.Questionnaire Q
JOIN dbo.QuestionnaireDefinition QRD
ON QRD.QuestionnaireDefinitionID = Q.QuestionnaireDefinitionID
AND QRD.Name = 'Internal Admin'
LEFT JOIN QuestionDefinition QD
ON Q.QuestionnaireDefinitionID = QD.QuestionnaireDefinitionID
AND QD.QuestionDefinitionID = 5968
LEFT OUTER JOIN Answer A
ON A.QuestionnaireID = Q.QuestionnaireID
AND A.QuestionDefinitionID = QD.QuestionDefinitionID
WHERE Q.IsActive = 1
AND Q.SubscriberID = 240
AND Q.AccountID = Patient.AccountID
),
[IntAdmFormCreatedDate]= Q.DateCreated,
[HasAdminForm] = 'Yes',
[CreatedByUser] = PatientCreatedBy.Name
FROM dbo.Account AS Patient
JOIN dbo.AccountRating
ON Patient.AccountRatingID = AccountRating.AccountRatingID
JOIN dbo.AccountType
ON Patient.AccountTypeID = AccountType.AccountTypeID
JOIN dbo.[User] Region
ON Patient.UserID = Region.UserID
JOIN dbo.[User] PatientCreatedBy
ON Patient.CreatedBy = PatientCreatedBy.UserID
JOIN dbo.Questionnaire Q
ON Patient.AccountID = Q.AccountID
WHERE Patient.SubscriberID = 240
AND (Q.DateCreated < DATEADD(D, 26, DATEADD(MONTH, DATEDIFF(MONTH, CONVERT(DATETIME, '1900-01-01 00:00:00', 102), GETDATE()), CONVERT(DATETIME, '1900-01-01 00:00:00', 102))))
AND Q.QuestionnaireDefinitionID = 235
AND Q.IsActive = 1
AND Region.FirstName <> 'Rubbish'
UNION SELECT [Region] = Region.FirstName,
[Patient] = Patient.Name,
[PatientStatus] = AccountRating.Name,
[MedicalAid] = AccountType.Name,
[QuoteAmount] = '0',
[InvoiceAmount] = '0',
[DateSubmitted] = '',
[DateApprovedDeclined] = '',
[IntAdmFormCreatedDate] = '',
[HasAdminForm] = 'No',
[CreatedByUser] = PatientCreatedBy.Name
FROM dbo.Account AS Patient
JOIN dbo.AccountRating
ON Patient.AccountRatingID = AccountRating.AccountRatingID
JOIN dbo.AccountType
ON Patient.AccountTypeID = AccountType.AccountTypeID
JOIN dbo.[User] AS Region
ON Patient.UserID = Region.UserID
JOIN dbo.[User] AS PatientCreatedBy
ON Patient.CreatedBy = PatientCreatedBy.UserID
WHERE NOT EXISTS( SELECT *
FROM Questionnaire AS Q
WHERE Patient.AccountID = Q.AccountID
AND Q.QuestionnaireDefinitionID = 235
AND Patient.SubscriberID = 240
AND Q.SubscriberID = 240
)
AND Patient.SubscriberID = 240
AND Patient.DateCreated < DATEADD(D, 26, DATEADD(MONTH, DATEDIFF(MONTH, CONVERT(DATETIME, '1900-01-01 00:00:00', 102), GETDATE()), CONVERT(DATETIME, '1900-01-01 00:00:00', 102)))
AND Region.FirstName <> 'Rubbish'
Here is another version of the query I tried, but also runs the same time.
SELECT [Region] = Region.FirstName,
[Patient] = Patient.Name,
[PatientStatus] = AccountRating.Name,
[MedicalAid] = AccountType.Name,
[QuoteAmount] = Q1.Response,
[InvoiceAmount] = Q2.Response,
[DateSubmitted] = Q3.Response,
[DateApprovedDeclined] = Q4.Response,
[IntAdmFormCreatedDate]= Q.DateCreated,
[HasAdminForm] = 'Yes',
[CreatedByUser] = PatientCreatedBy.Name
FROM dbo.Account AS Patient
JOIN dbo.AccountRating
ON Patient.AccountRatingID = AccountRating.AccountRatingID
JOIN dbo.AccountType
ON Patient.AccountTypeID = AccountType.AccountTypeID
JOIN dbo.[User] Region
ON Patient.UserID = Region.UserID
JOIN dbo.[User] PatientCreatedBy
ON Patient.CreatedBy = PatientCreatedBy.UserID
JOIN dbo.Questionnaire Q
ON Patient.AccountID = Q.AccountID
OUTER APPLY
(
SELECT TOP 1 Q.AccountID,
A.Response
FROM dbo.Questionnaire Q
JOIN dbo.QuestionnaireDefinition QRD
ON QRD.QuestionnaireDefinitionID = Q.QuestionnaireDefinitionID
AND QRD.Name = 'Internal Admin'
LEFT JOIN QuestionDefinition QD
ON Q.QuestionnaireDefinitionID = QD.QuestionnaireDefinitionID
AND QD.QuestionDefinitionID = 5966
LEFT OUTER JOIN Answer A
ON A.QuestionnaireID = Q.QuestionnaireID
AND A.QuestionDefinitionID = QD.QuestionDefinitionID
WHERE Q.IsActive = 1
Q.SubscriberID = 240
AND Q.AccountID = Patient.AccountID
) Q1
OUTER APPLY
(
SELECT TOP 1 Q.AccountID,
A.Response
FROM dbo.Questionnaire Q
JOIN dbo.QuestionnaireDefinition QRD
ON QRD.QuestionnaireDefinitionID = Q.QuestionnaireDefinitionID
AND QRD.Name = 'Internal Admin'
LEFT JOIN QuestionDefinition QD
ON Q.QuestionnaireDefinitionID = QD.QuestionnaireDefinitionID
AND QD.QuestionDefinitionID = 5969
LEFT OUTER JOIN Answer A
ON A.QuestionnaireID = Q.QuestionnaireID
AND A.QuestionDefinitionID = QD.QuestionDefinitionID
WHERE Q.IsActive = 1
AND Q.AccountID = Patient.AccountID
) Q2
OUTER APPLY
(
SELECT TOP 1 Q.AccountID,
A.Response
FROM dbo.Questionnaire Q
JOIN dbo.QuestionnaireDefinition QRD
ON QRD.QuestionnaireDefinitionID = Q.QuestionnaireDefinitionID
AND QRD.Name = 'Internal Admin'
LEFT JOIN QuestionDefinition QD
ON Q.QuestionnaireDefinitionID = QD.QuestionnaireDefinitionID
AND QD.QuestionDefinitionID = 5965
LEFT OUTER JOIN Answer A
ON A.QuestionnaireID = Q.QuestionnaireID
AND A.QuestionDefinitionID = QD.QuestionDefinitionID
WHERE Q.IsActive = 1
AND Q.AccountID = Patient.AccountID
) Q3
OUTER APPLY
(
SELECT TOP 1 Q.AccountID,
A.Response
FROM dbo.Questionnaire Q
JOIN dbo.QuestionnaireDefinition QRD
ON QRD.QuestionnaireDefinitionID = Q.QuestionnaireDefinitionID
AND QRD.Name = 'Internal Admin'
LEFT JOIN QuestionDefinition QD
ON Q.QuestionnaireDefinitionID = QD.QuestionnaireDefinitionID
AND QD.QuestionDefinitionID = 5968
LEFT OUTER JOIN Answer A
ON A.QuestionnaireID = Q.QuestionnaireID
AND A.QuestionDefinitionID = QD.QuestionDefinitionID
WHERE Q.IsActive = 1
AND Q.AccountID = Patient.AccountID
) Q4
WHERE Patient.SubscriberID = 240
AND (Q.DateCreated < DATEADD(D, 26, DATEADD(MONTH, DATEDIFF(MONTH, CONVERT(DATETIME, '1900-01-01 00:00:00', 102), GETDATE()), CONVERT(DATETIME, '1900-01-01 00:00:00', 102))))
AND Q.QuestionnaireDefinitionID = 235
AND Q.IsActive = 1
AND Region.FirstName <> 'Rubbish'
UNION SELECT [Region] = Region.FirstName,
[Patient] = Patient.Name,
[PatientStatus] = AccountRating.Name,
[MedicalAid] = AccountType.Name,
[QuoteAmount] = '0',
[InvoiceAmount] = '0',
[DateSubmitted] = '',
[DateApprovedDeclined] = '',
[IntAdmFormCreatedDate] = '',
[HasAdminForm] = 'No',
[CreatedByUser] = PatientCreatedBy.Name
FROM dbo.Account AS Patient
JOIN dbo.AccountRating
ON Patient.AccountRatingID = AccountRating.AccountRatingID
JOIN dbo.AccountType
ON Patient.AccountTypeID = AccountType.AccountTypeID
JOIN dbo.[User] AS Region
ON Patient.UserID = Region.UserID
JOIN dbo.[User] AS PatientCreatedBy
ON Patient.CreatedBy = PatientCreatedBy.UserID
WHERE NOT EXISTS( SELECT *
FROM Questionnaire AS Q
WHERE Patient.AccountID = Q.AccountID
AND Q.QuestionnaireDefinitionID = 235
AND Patient.SubscriberID = 240
AND Q.SubscriberID = 240
)
AND Patient.SubscriberID = 240
AND Patient.DateCreated < DATEADD(D, 26, DATEADD(MONTH, DATEDIFF(MONTH, CONVERT(DATETIME, '1900-01-01 00:00:00', 102), GETDATE()), CONVERT(DATETIME, '1900-01-01 00:00:00', 102)))
AND Region.FirstName <> 'Rubbish'

Your Scalar Subqueries all share the same joins, just the QD.QuestionDefinitionID differs.
You can rewrite those 4 TOPs with a single Derived Table and join to it instead:
...
LEFT JOIN
(
SELECT
Q.AccountID,
MAX(CASE WHEN QD.QuestionDefinitionID = 5966 THEN A.Response END) AS [DateSubmitted]
MAX(CASE WHEN QD.QuestionDefinitionID = 5968 THEN A.Response END) AS [DateApprovedDeclined]
...
FROM dbo.Questionnaire Q
JOIN dbo.QuestionnaireDefinition QRD
ON QRD.QuestionnaireDefinitionID = Q.QuestionnaireDefinitionID
AND QRD.NAME = 'Internal Admin'
LEFT JOIN QuestionDefinition QD
ON Q.QuestionnaireDefinitionID = QD.QuestionnaireDefinitionID
LEFT OUTER JOIN Answer A
ON A.QuestionnaireID = Q.QuestionnaireID
AND A.QuestionDefinitionID = QD.QuestionDefinitionID
WHERE Q.IsActive = 1
AND Q.SubscriberID = 240
GROUP BY Q.AccountID
) AS Q
ON Q.AccountID = Patient.AccountID
I used MAX because you didn't have ORDER BY in you subqueries, so the exact value either doesn't matter or there's only a single row per value.

Related

Wrap CTE inside another Select statement

Is it possible to wrap a CTE inside of another Select statement?
Here is my CTE:
WITH IRS AS
(SELECT BUSINESS_UNIT, VOUCHER_ID, VOUCHER_LINE_NUM, WTHD_ENTITY, WTHD_TYPE, WTHD_CLASS
FROM PS_VCHR_LINE_WTHD
WHERE WTHD_ENTITY = 'IRS' ) ,
PA AS
(SELECT BUSINESS_UNIT, VOUCHER_ID, VOUCHER_LINE_NUM, WTHD_ENTITY, WTHD_TYPE, WTHD_CLASS
FROM PS_VCHR_LINE_WTHD
WHERE WTHD_ENTITY = 'PA' )
SELECT IRS_WTHD.BUSINESS_UNIT, IRS_WTHD.VOUCHER_ID, IRS_WTHD.VOUCHER_LINE_NUM,
--COLUMN 1 TO BE USED IN MAIN QUERY:
CASE WHEN PA_WTHD.WTHD_ENTITY = 'PA' THEN 'PA'
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099N'
AND IRS_WTHD.WTHD_CLASS = '01' THEN 'IRS'
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099'
AND IRS_WTHD.WTHD_CLASS = '07' THEN 'IRS'
ELSE ''
END ,
--COLUMN 2 TO BE USED IN MAIN QUERY:
CASE WHEN PA_WTHD.WTHD_ENTITY = 'PA' THEN CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ','0') AS VARCHAR)
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099N'
AND IRS_WTHD.WTHD_CLASS = '01' THEN 'MISC' + CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ', '0') AS VARCHAR)
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099'
AND IRS_WTHD.WTHD_CLASS = '07' THEN 'MISC7'
WHEN PA_WTHD.WTHD_ENTITY = '' THEN ''
ELSE 'MISC' + CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ', '0') AS VARCHAR)
END
FROM IRS IRS_WTHD
LEFT JOIN PA PA_WTHD ON PA_WTHD.BUSINESS_UNIT = IRS_WTHD.BUSINESS_UNIT AND PA_WTHD.VOUCHER_ID = IRS_WTHD.VOUCHER_ID AND PA_WTHD.VOUCHER_LINE_NUM = IRS_WTHD.VOUCHER_LINE_NUM
I would like to wrap the above CTE inside of this main SQL Select statement below and output the two CASE statement columns above into the final SELECT statement below while joining on BUSINESS_UNIT, VOUCHER_ID, and VOUCHER_LINE_NUM fields from the PS_VCHR_LINE_WTHD table :
--Main Select Statement:
SELECT CONCAT(A.BUSINESS_UNIT,A.VOUCHER_ID) AS INVOICE_ID, A.VOUCHER_LINE_NUM,
CASE WHEN EXISTS (SELECT 1 FROM PS_DISTRIB_LINE
WHERE BUSINESS_UNIT = A.BUSINESS_UNIT
AND VOUCHER_ID = A.VOUCHER_ID
AND VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM)
THEN 'ITEM' ELSE 'MISCELLANEOUS' END, A.MERCHANDISE_AMT, B.QTY_VCHR, A.UNIT_PRICE, A.UNIT_OF_MEASURE, A.DESCR, A.PO_ID, A.LINE_NBR,
A.SCHED_NBR, B.PO_DIST_LINE_NUM, A.DESCR254_MIXED, '','',
F.OR_ENTITY + '.' + F.OR_LOCATION + '.' + CASE WHEN B.BUSINESS_UNIT_GL IN ('90000', '90032', '90059') AND H.DEPTID = '741' THEN H.COST_CENTER
WHEN B.BUSINESS_UNIT_GL = '90000' AND H.DEPTID = '956' THEN H.COST_CENTER
WHEN B.DEPTID IN ('882', '883', '884', '885', '886', '803' , '887', '888') THEN '676'
ELSE '000' END
+ '.' + B.ACCOUNT + '.' + ISNULL(G.ORACLE_PROJECT_CODE,'000000000.') + ISNULL(NULLIF(B.AFFILIATE, ''), '00000.') + '.000000.' + '000000' ,'', C.ACCOUNTING_DT, '',
'','','', ISNULL(D.WTHD_ENTITY,''), '', '', '', A.SALETX_AMT
FROM PS_VOUCHER_LINE A
LEFT OUTER JOIN PS_DISTRIB_LINE B ON B.BUSINESS_UNIT = A.BUSINESS_UNIT AND B.VOUCHER_ID = A.VOUCHER_ID AND B.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VOUCHER C ON C.BUSINESS_UNIT = A.BUSINESS_UNIT AND C.VOUCHER_ID = A.VOUCHER_ID
LEFT OUTER JOIN PS_VCHR_LINE_WTHD D ON D.BUSINESS_UNIT = A.BUSINESS_UNIT AND D.VOUCHER_ID = A.VOUCHER_ID AND D.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VENDOR E ON E.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND E.VENDOR_ID = A.VENDOR_ID
LEFT OUTER JOIN #CloudXWalk F ON F.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND (F.DEPTID = 'All' OR F.DEPTID = B.DEPTID)
LEFT OUTER JOIN #CloudCostCenter H ON H.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND H.DEPTID = B.DEPTID
LEFT OUTER JOIN #CloudProjectCodes G ON G.PS_PROJECT_CODE = B.PROJECT_ID
LEFT OUTER JOIN PS_PYMNT_VCHR_XREF I ON I.BUSINESS_UNIT = A.BUSINESS_UNIT AND I.VOUCHER_ID = A.VOUCHER_ID
WHERE C.INVOICE_DT > '01-03-2019'
AND I.PYMNT_ID = ''
AND C.CLOSE_STATUS <> 'C'
AND C.ENTRY_STATUS <> 'X'
ORDER BY 1,2
Is this possible, or is there an alternate way of avoiding using the CTE? I am using the CTE because I need to be able to run Case statements across multiple rows and possibly return data on other rows.

Msg 245, Level 16, State 1, Procedure SYNC_ri_res_to_WC_PersonAddress, Line 24 [Batch Start Line 0] Conversion failed when converting the

When I run the following query:
update ri_res
set name_last = 'onion',
name_first = 'Forest',
addr1 = '2872 Loki Laufeyson',
city = 'Queens',
[state] = 'NY',
zip = '11374',
county = 'West',
phone = '4152366293',
ssn = '912308719',
sex = 'M',
birthplace = 'Madison',
birth_date = '3/1/1947',
uniqueid = newid()
where cono = 'JC' and resno = '216'
I am getting the following error:
Msg 245, Level 16, State 1, Procedure SYNC_ri_res_to_WC_PersonAddress,
Line 24 [Batch Start Line 0] Conversion failed when converting the
varchar value '1094_2' to data type int.
Listed below is the stored procedure:
USE [WestCounty]
GO
/****** Object: StoredProcedure [Base360].[SYNC_ri_res_to_WC_PersonAddress] Script Date: 2/25/2019 9:12:39 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [Base360].[SYNC_ri_res_to_WC_PersonAddress]
#ConoResnos XML
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Payload as XML = #ConoResnos;
/* Address (ri_res address fields) */
INSERT INTO Base360.Address_Base (Address1, Address2, City, AddressStateID, Zipcode, AddressCountyID, EnterpriseID)
select distinct i.addr1, i.addr2, i.city, S.AddressStateID, i.zip, county.AddressCountyID,(select top 1 EnterpriseID from Base360.Facility_Base where FacilityID > 0)
FROM ri_res i with(nolock)
INNER JOIN (SELECT x.value('cono[1]','varchar(4)') as cono, x.value('resno[1]','INT') as resno FROM #Payload.nodes('/Inserted/Row') AS T(x)) as cr
on cr.cono = i.cono and cr.resno = i.resno
LEFT OUTER JOIN [Base360].[AddressState] S ON i.state = S.StateCode
LEFT OUTER JOIN Base360.AddressCounty county on i.county = county.CountyName and S.AddressStateID = county.AddressStateID
LEFT OUTER JOIN [Base360].[Address_Base] A with(nolock)
ON ISNULL(addr1,'') = ISNULL(A.Address1 ,'')
AND isnull(addr2,'') = isnull(A.Address2,'')
AND isnull(S.AddressStateID,'') = ISNULL(A.AddressStateID,'')
AND isnull(i.city,'') = isnull(A.City,'')
AND isnull(SUBSTRING(i.[zip], 1, 5),'') = isnull(SUBSTRING(A.ZipCode,1,5),'')
AND isnull(county.AddressCountyID,'') = ISNULL(A.AddressCountyID,'')
WHERE A.AddressID IS NULL and (i.addr1 is not null or i.addr2 is not null OR i.city is not null or i.state is not null or i.zip is not null or i.county is not null)
UPDATE PA SET EndDAte = GetUTCDate()
FROM ri_res rc with(nolock)
INNER JOIN (SELECT x.value('cono[1]','varchar(4)') as cono, x.value('resno[1]','INT') as resno FROM #Payload.nodes('/Inserted/Row') AS T(x)) as cr
on cr.cono = rc.cono and cr.resno = rc.resno
INNER JOIN Base360.PersonIdentification PID with(nolock) on rc.cono = SUBSTRING(PID.PersonIdentificationValue, 0,(charindex('_',PID.PersonIdentificationValue)))
AND rc.resno = CAST(SUBSTRING(PID.PersonIdentificationValue, (charindex('_',PID.PersonIdentificationValue))+1,10) as int)
AND PID.PersonIdentificationTypeID = -1
INNER JOIN Base360.PersonAddress PA on PID.PersonID = PA.PersonID and PA.AddressTypeID = -2 and PA.EndDate IS NULL
;with addyCTEInsert2 as (
select ROW_NUMBER() OVER (Partition by isnull(A.Address1,''), isnull(A.Address2,''), isnull(A.City,''), ISNULL(A.AddressStateID,''), isnull(SUBSTRING(A.ZipCode,1,5),''), isnull(county.CountyName,'') ORDER BY CreateUTCDate) as RowNum,
A.AddressID, A.Address1, A.Address2, A.City, A.AddressStateID, A.Zipcode, county.AddressCountyID
FROM ri_res i with(nolock)
INNER JOIN (SELECT x.value('cono[1]','varchar(4)') as cono, x.value('resno[1]','INT') as resno FROM #Payload.nodes('/Inserted/Row') AS T(x)) as cr
on cr.cono = i.cono and cr.resno = i.resno
LEFT OUTER JOIN [Base360].[AddressState] S ON i.state = S.StateCode
LEFT OUTER JOIN Base360.AddressCounty county on i.county = county.CountyName and S.AddressStateID = county.AddressStateID
INNER JOIN [Base360].[Address_Base] A with(nolock)
ON ISNULL(addr1,'') = ISNULL(A.Address1 ,'')
AND isnull(addr2,'') = isnull(A.Address2,'')
AND isnull(S.AddressStateID,'') = ISNULL(A.AddressStateID,'')
AND isnull(i.city,'') = isnull(A.City,'')
AND isnull(SUBSTRING(i.[zip], 1, 5),'') = isnull(SUBSTRING(A.ZipCode,1,5),'')
AND isnull(county.AddressCountyID,'') = ISNULL(A.AddressCountyID,'')
WHERE (i.addr1 is not null or i.addr2 is not null OR i.city is not null or i.state is not null or i.zip is not null or i.county is not null)
)
INSERT INTO Base360.PersonAddress ([PersonID], [AddressID], [AddressTypeID], [BeginDate], [EnterpriseID])
select distinct PB.PersonID, AB.AddressID, -2 AS AddressTypeID, GetUTCDate() AS BeginDate, PB.EnterpriseID
FROM ri_res rc with(nolock)
INNER JOIN Base360.PersonIdentification PID with(nolock) on rc.cono = SUBSTRING(PID.PersonIdentificationValue, 0,(charindex('_',PID.PersonIdentificationValue)))
AND rc.resno = CAST(SUBSTRING(PID.PersonIdentificationValue, (charindex('_',PID.PersonIdentificationValue))+1,10) as int)
AND PID.PersonIdentificationTypeID = -1
INNER JOIN [Base360].[Person_Base] PB with(nolock) ON PID.PersonID = PB.PersonID
LEFT OUTER JOIN [Base360].[AddressState] S ON rc.state = S.StateCode
LEFT OUTER JOIN Base360.AddressCounty county on rc.county = county.CountyName and s.AddressStateID = county.AddressStateID
INNER JOIN addyCTEInsert2 AB
ON ISNULL(rc.addr1,'') = ISNULL(AB.Address1 ,'')
AND isnull(rc.addr2,'') = isnull(AB.Address2,'')
AND isnull(S.AddressStateID,'') = ISNULL(AB.AddressStateID,'')
AND isnull(rc.city,'') = isnull(AB.City,'')
AND isnull(SUBSTRING(rc.[zip], 1, 5),'') = isnull(SUBSTRING(AB.ZipCode,1,5),'')
AND isnull(county.AddressCountyID,'') = ISNULL(AB.AddressCountyID,'')
and ab.rownum = 1
INNER JOIN (SELECT x.value('cono[1]','varchar(4)') as cono, x.value('resno[1]','INT') as resno FROM #Payload.nodes('/Inserted/Row') AS T(x)) as cr
on cr.cono = rc.cono and cr.resno = rc.resno
LEFT OUTER JOIN Base360.PersonAddress pa with(nolock) on PB.PersonID = pa.personid and pa.AddressTypeID = -2 and pa.EndDate is null and AB.AddressID = pa.AddressID
WHERE pa.PersonAddressID IS NULL AND (rc.[name_first] IS NOT NULL OR rc.[name_last] IS NOT NULL)
END

SQL Not In sub Query

I have a situation where I need to select prospects (relationship of 'P') from our MEMBERS table for a particular site. However, when I select these people, I need to exclude two groups of those prospects. Each of these groups have entries in a separate table named MEMBERUDFS. Now not all entries in the MEMBERS table will have an entry in the MEMBERUDFS table. Therefore, I tried to exclude those groups from the main query by using two "NOT IN" subqueries but that does not seem to work. I am able to isolate the exclusion group with the following queries:
SELECT MEMBERS_1.memid
FROM MEMBERS AS MEMBERS_1
JOIN SITES AS SITES_1 ON MEMBERS_1.siteid = SITES_1.siteid
LEFT JOIN MEMBERUDFS AS MEMBERUDFS_1 ON MEMBERS_1.memid = MEMBERUDFS_1.memid
JOIN MEMBERUDFSETUPS AS MEMBERUDFSETUPS_1 ON MEMBERUDFS_1.udfid = MEMBERUDFSETUPS_1.udfid
WHERE (MEMBERS_1.relationship = 'P')
AND (MEMBERS_1.email <> '')
AND (MEMBERUDFS_1.udfid = '26')
AND (MEMBERUDFS_1.udfvalue = 'No')
AND (MEMBERS_1.entrydate < DATEADD(DAY, -6, GETDATE()))
AND (MEMBERS_1.siteid = #rvSite)
And This query:
SELECT MEMBERS_2.memid
FROM MEMBERS AS MEMBERS_2
JOIN SITES AS SITES_2 ON MEMBERS_2.siteid = SITES_2.siteid
LEFT JOIN MEMBERUDFS AS MEMBERUDFS_2 ON MEMBERS_2.memid = MEMBERUDFS_2.memid
JOIN MEMBERUDFSETUPS AS MEMBERUDFSETUPS_2 ON MEMBERUDFS_2.udfid = MEMBERUDFSETUPS_2.udfid
WHERE (MEMBERS_2.relationship = 'P')
AND (MEMBERS_2.email <> '')
AND (MEMBERUDFS_2.udfid = '25')
AND (MEMBERUDFS_2.udfvalue = 'Yes')
AND (MEMBERS_2.entrydate < DATEADD(DAY, -21, GETDATE()))
AND (MEMBERS_2.siteid = #rvSite)
SO THIS IS WHAT I HAD PUT TOGETHER, BUT IT DOES NOT ELIMINATE THE TWO SUBQUERY GROUPS:
SELECT MEMBERS.scancode,
MEMBERS.memid,
MEMBERS.fname,
MEMBERS.lname,
MEMBERS.relationship,
MEMBERS.status,
MEMBERS.email,
MEMBERS.entrydate,
SITES.sitename
FROM MEMBERS
JOIN SITES ON MEMBERS.siteid = SITES.siteid
WHERE (MEMBERS.relationship = 'P')
AND (MEMBERS.email <> '')
AND (MEMBERS.siteid = #rvSite)
AND (MEMBERS.memid NOT IN (
SELECT MEMBERS_1.memid
FROM MEMBERS AS MEMBERS_1
JOIN SITES AS SITES_1 ON MEMBERS_1.siteid = SITES_1.siteid
LEFT JOIN MEMBERUDFS AS MEMBERUDFS_1 ON MEMBERS_1.memid = MEMBERUDFS_1.memid
JOIN MEMBERUDFSETUPS AS MEMBERUDFSETUPS_1 ON MEMBERUDFS_1.udfid = MEMBERUDFSETUPS_1.udfid
WHERE (MEMBERS_1.relationship = 'P')
AND (MEMBERS_1.email <> '')
AND (MEMBERUDFS_1.udfid = '26')
AND (MEMBERUDFS_1.udfvalue = 'No')
AND (MEMBERS_1.entrydate < DATEADD(DAY, -6, GETDATE()))
AND (MEMBERS_1.siteid = #rvSite))
)
AND (MEMBERS.memid NOT IN (
SELECT MEMBERS_2.memid
FROM MEMBERS AS MEMBERS_2
JOIN SITES AS SITES_2 ON MEMBERS_2.siteid = SITES_2.siteid
LEFT JOIN MEMBERUDFS AS MEMBERUDFS_2 ON MEMBERS_2.memid = MEMBERUDFS_2.memid
JOIN MEMBERUDFSETUPS AS MEMBERUDFSETUPS_2 ON MEMBERUDFS_2.udfid = MEMBERUDFSETUPS_2.udfid
WHERE (MEMBERS_2.relationship = 'P')
AND (MEMBERS_2.email <> '')
AND (MEMBERUDFS_2.udfid = '25')
AND (MEMBERUDFS_2.udfvalue = 'Yes')
AND (MEMBERS_2.entrydate < DATEADD(DAY, -21, GETDATE()))
AND (MEMBERS_2.siteid = #rvSite))
)
Any help would be appreciated
You just need to play with your where clause...
AND (MEMBERS.memid NOT IN (
SELECT MEMBERS_1.memid
FROM MEMBERS AS MEMBERS_1
JOIN SITES AS SITES_1 ON MEMBERS_1.siteid = SITES_1.siteid
LEFT JOIN MEMBERUDFS AS MEMBERUDFS_1 ON MEMBERS_1.memid = MEMBERUDFS_1.memid
JOIN MEMBERUDFSETUPS AS MEMBERUDFSETUPS_1 ON MEMBERUDFS_1.udfid = MEMBERUDFSETUPS_1.udfid
WHERE (MEMBERS_1.relationship = 'P')
AND (MEMBERS_1.email <> '')
AND (MEMBERS_1.siteid = #rvSite)
AND (((MEMBERUDFS_1.udfid = '26') AND (MEMBERUDFS_1.udfvalue = 'No') AND (MEMBERS_1.entrydate < DATEADD(DAY, -6, GETDATE()))) OR
((MEMBERUDFS_1.udfid = '25') AND (MEMBERUDFS_1.udfvalue = 'Yes') AND (MEMBERS_1.entrydate < DATEADD(DAY, -21, GETDATE()))))

Optimize query with sql server

I have the following query .its execution took 15 min .It is too much slowly .
Is there a way to optimize it ?
Query
SELECT
Id,Fees,WeekOfMonth,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate,'Temp Fees ' AS FeesName
,#MonthName AS [MonthName]
INTO ##TempFeesMonthly
from
(
SELECT DISTINCT
1 as Id,sum(((CNTI_THPAYE *(CNTI_THFACT / CNTI_THPAYE)) *
(CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*#NumberOfDays)) AS Fees,WeekOfMonth,StartDate,EndDate
FROM SCHHAYS.dbo.WTVTAT TAT
LEFT JOIN
SCHHAYS.dbo.WTTIEINT INT
ON (
TAT.TIE_ID = INT.TIE_ID
)
AND (
TAT.VTAT_IORDRE = INT.TIEI_ORDRE
)
LEFT JOIN
SCHHAYS.dbo.PYCONTRAT CC
ON TAT.PER_ID = CC.PER_ID
AND TAT.CNT_ID = CC.CNT_ID
LEFT JOIN
SCHHAYS.dbo.CMTIERS T
ON TAT.TIE_ID = T.TIE_ID
LEFT JOIN
SCHHAYS.dbo.WTMISS M
ON CC.PER_ID = M.PER_ID
AND CC.CNT_ID = M.CNT_ID
LEFT JOIN
##WTCNTIWeek COT1
ON M.PER_ID = COT1.PER_ID
AND M.CNT_ID = COT1.CNT_ID
INNER JOIN
SCHHAYS.dbo.WTPRH AS PRH
ON M.PER_ID = PRH.PER_ID
AND M.CNT_ID = PRH.CNT_ID
AND M.TIE_ID = PRH.TIE_ID
INNER JOIN
##tempStartEndWeekDates AS Tsed
ON PRH_DTEDEBSEM>=Tsed.StartDate
AND PRH_DTEFINSEM<=Tsed.EndDate
LEFT JOIN
SCHHAYS.dbo.WTSCCT C
ON CC.RGPCNT_ID = C.RGPCNT_ID
AND CC.PER_ID = C.PER_ID
AND CC.CNT_ID = C.CNT_ID
INNER JOIN
##TempHaysStaffWeek HF
ON C.VAPO_CODE = HF.onetouch COLLATE Latin1_General_CI_AS
group by
WeekOfMonth,StartDate,EndDate)t
--CREATE INDEX IDX_TempFeesMonthly ON ##TempFeesMonthly(WeekOfMonth)
--Calcul Temp Margin
UNION ALL
--INSERT INTO ##TempFeesMonthly(Id,Fees,WeekOfMonth,StartDate,EndDate,FeesName,[MonthName])
SELECT
2, sum(Fees) AS Fees ,WeekOfMonth,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate,'Temp Margin ' AS FeesName
,#MonthName AS [MonthName]
from
(
SELECT DISTINCT
sum((CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*#NumberOfDays)-(CNTI_THPAYE *(CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*1.453*1.21*#NumberOfDays) AS Fees,WeekOfMonth,StartDate,EndDate
FROM SCHHAYS.dbo.WTVTAT TAT
LEFT JOIN
SCHHAYS.dbo.WTTIEINT INT
ON (
TAT.TIE_ID = INT.TIE_ID
)
AND (
TAT.VTAT_IORDRE = INT.TIEI_ORDRE
)
LEFT JOIN
SCHHAYS.dbo.PYCONTRAT CC
ON TAT.PER_ID = CC.PER_ID
AND TAT.CNT_ID = CC.CNT_ID
LEFT JOIN
SCHHAYS.dbo.CMTIERS T
ON TAT.TIE_ID = T.TIE_ID
LEFT JOIN
SCHHAYS.dbo.WTMISS M
ON CC.PER_ID = M.PER_ID
AND CC.CNT_ID = M.CNT_ID
LEFT JOIN
##WTCNTIWeek COT1
ON M.PER_ID = COT1.PER_ID
AND M.CNT_ID = COT1.CNT_ID
INNER JOIN
SCHHAYS.dbo.WTPRH AS PRH
ON M.PER_ID = PRH.PER_ID
AND M.CNT_ID = PRH.CNT_ID
AND M.TIE_ID = PRH.TIE_ID
INNER JOIN
##tempStartEndWeekDates AS Tsed
ON PRH_DTEDEBSEM>=Tsed.StartDate
AND PRH_DTEFINSEM<=Tsed.EndDate
LEFT JOIN
SCHHAYS.dbo.WTSCCT C
ON CC.RGPCNT_ID = C.RGPCNT_ID
AND CC.PER_ID = C.PER_ID
AND CC.CNT_ID = C.CNT_ID
INNER JOIN
##TempHaysStaffWeek HF
ON C.VAPO_CODE = HF.onetouch COLLATE Latin1_General_CI_AS
group by
WeekOfMonth,StartDate,EndDate,CNTI_THPAYE,CNTI_DURHEBDO)t
GROUP BY WeekOfMonth,StartDate,EndDate

How to change this 'Not In' Query to Left Join query

I've been trying to change this query. I don't want to use 'Not In' in this query. Can anybody help me how to change this query to left join query?
SELECT t.date,t.ticket,t.weight,t.Count, td.description
FROM tblticket t inner join tblticketdetails td on t.ticket = td.ticket
WHERE t.ticket NOT IN (SELECT r.Original_ticket from tblRenew R where isnull(r.new_ticket,'') = '' and r.transaction_status = 'valid')
AND RTRIM(LTRIM(t.status)) = 'OPEN'
AND td.Type = 62
AND t.weight/t.Count >= 1000
AND t.date BETWEEN '2011-12-31' AND '2013-01-17'
Providing that you don't have multiple records in tblRenew for any ticket:
select
t.date, t.ticket, t.weight, t.Count, td.description
from
tblticket t
inner join tblticketdetails td on t.ticket = td.ticket
left join tblRenew R on isnull(r.new_ticket,'') = '' and r.transaction_status = 'valid' and r.Original_ticket = t.ticket
where
r.Original_ticket is not null
and RTRIM(LTRIM(t.status)) = 'OPEN'
and td.Type = 62
and t.weight/t.Count >= 1000
and t.date BETWEEN '2011-12-31' AND '2013-01-17'
SELECT t.date, t.ticket,t.weight, t.Count, td.description
FROM tblticket t inner join
tblticketdetails td
on t.ticket = td.ticket left outer join
(SELECT r.Original_ticket
from tblRenew R
where isnull(r.new_ticket,'') = '' and
r.transaction_status = 'valid'
) v
on t.ticket = v.Original_ticket
WHERE t.ticket NOT IN (SELECT r.Original_ticket from tblRenew R where isnull(r.new_ticket,'') = '' and r.transaction_status = 'valid')
AND RTRIM(LTRIM(t.status)) = 'OPEN'
AND td.Type = 62
AND t.weight/t.Count >= 1000
AND t.date BETWEEN '2011-12-31' AND '2013-01-17'
and v.original_tiket is null