Get results only if it exists in a union tsql - sql

So I have the following select that will output datametrics and I have a Union as well
SELECT DISTINCT (SELECT DATEADD(DAY,-1,DATEADD(MONTH,DATEDIFF(MONTH,0,MAX(GreatestDate)) + 1, 0))
FROM
(VALUES (max(th.TransactionEffectiveDt)),(max(bp.EffectiveDt)),(max(th.TransactionDt))) AS Value(GreatestDate)) AS BookDate
,th.Transactioncd TransactionType
,bp.PolicyNumber PolicyNumber
,cast(bp.EffectiveDt AS DATE) EffectiveDate
,max(cast(th.TransactionEffectiveDt AS DATE)) TransactionEffectiveDate
,NULL
,th.TransactionNumber TransactionNumber
,cast(bp.ExpirationDt AS DATE) ExpirationDate
,replace(UPPER(ni.IndexName), ',', '') InsuredName
,replace(isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), ''), ',', '') InsuredStreetAddress
,UPPER(ad.City) InsuredCity
,UPPER(ad.StateProvCd) InsuredState
,ad.PostalCode InsuredZipCode
,i.EntityTypeCd InsuredType
,isnull(tr.ReasonCd, '') ReasonCode
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4)) ProrateFactor
,'0'
,'0'
,'0'
,bd.YearBuilt YrConstruction
,ln.PROPDed + '%' [% loss ded EQ]
,CAST(bd.BldgNumber AS VARCHAR(255)) BldgNumber
,CONVERT(INT,REPLACE(bd.BuildingValue,',','')) BuildingValue
,CONVERT(INT,REPLACE(bd.ContentsBLimit,',','')) ContentsBLimit
,CONVERT(INT,REPLACE(bd.ContentsCLimit,',','')) ContentsCLimit
,CONVERT(INT,REPLACE(bd.TIBLimit,',','')) TIBLimit
,CONVERT(INT,REPLACE(bd.BILimit,',','')) BILimit
,CONVERT(INT,REPLACE(bd.EDPLimit,',','')) EDPLimit
FROM java.basicpolicy bp
INNER JOIN java.nameinfo ni ON ni.SystemId = bp.SystemId
AND ni.CMMContainer = bp.CMMContainer
INNER JOIN java.line ln ON ln.CMMContainer = bp.CMMContainer
AND bp.SystemId = ln.SystemId
INNER JOIN java.risk r on r.SystemId=bp.SystemId
AND r.CMMContainer=bp.CMMContainer
AND r.ParentId=ln.Id
INNER JOIN java.building bd ON bd.CMMContainer = bp.CMMContainer
AND bd.SystemId = bp.SystemId
AND bd.ParentId=r.id
AND bd.[Status] = 'ACTIVE'
INNER JOIN java.addr ad ON ad.CMMContainer = ni.CMMContainer
AND bp.SystemId = ad.SystemId
AND ad.AddrTypeCd in ('RiskAddr')
AND ad.ParentId = bd.id
INNER JOIN java.transactioninfo th ON th.CMMContainer = bp.CMMContainer
AND th.SystemId = bp.SystemId
LEFT JOIN java.transactionreason tr ON tr.CMMContainer = bp.CMMContainer
AND TR.SystemId = bp.SystemId
AND TR.ParentId = th.ID
INNER JOIN java.insured i ON i.CMMContainer = bp.CMMContainer
AND i.SystemId = bp.SystemId
WHERE bp.CMMContainer = 'Application'
AND ni.NameTypeCd = 'INSUREDNAME'
AND (
th.TransactionCd IN (
'new business'
,'endorsement'
,'cancellation'
,'rewrite-new'
)
OR (
th.WrittenPremiumAmt IS NOT NULL
AND th.WrittenPremiumAmt <> 0
AND th.TransactionCd IN ('reinstatement')
)
)
AND bp.CarrierCd = 'ENIC'
AND th.TransactionNumber in (select distinct th.TransactionNumber
FROM java.basicpolicy bp
INNER JOIN java.nameinfo ni ON ni.SystemId = bp.SystemId
AND ni.CMMContainer = bp.CMMContainer
INNER JOIN java.line ln ON ln.CMMContainer = bp.CMMContainer
AND bp.SystemId = ln.SystemId
INNER JOIN java.building bd ON bd.CMMContainer = bp.CMMContainer
AND bd.SystemId = bp.SystemId
INNER JOIN java.addr ad ON ad.CMMContainer = ni.CMMContainer
AND bp.SystemId = ad.SystemId
AND ad.AddrTypeCd = 'InsuredMailingAddr'
INNER JOIN java.transactionhistory th ON th.CMMContainer = bp.CMMContainer
AND th.SystemId = bp.SystemId
LEFT JOIN java.transactionreason tr ON tr.CMMContainer = bp.CMMContainer
AND TR.SystemId = bp.SystemId
AND TR.ParentId = th.ID
INNER JOIN java.insured i ON i.CMMContainer = bp.CMMContainer
AND i.SystemId = bp.SystemId
WHERE bp.CMMContainer = 'policy'
AND ni.NameTypeCd = 'INSUREDNAME'
AND (
th.TransactionCd IN (
'new business'
,'endorsement'
,'cancellation'
,'rewrite-new'
)
OR (
th.WrittenPremiumAmt IS NOT NULL
AND th.WrittenPremiumAmt <> 0
AND th.TransactionCd IN ('reinstatement')
)
)
AND bp.CarrierCd = 'ENIC')
GROUP BY
th.Transactioncd
,bp.PolicyNumber
,cast(bp.EffectiveDt AS DATE)
,th.TransactionNumber
,cast(bp.ExpirationDt AS DATE)
,UPPER(ni.IndexName)
,isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), '')
,UPPER(ad.City)
,UPPER(ad.StateProvCd)
,ad.PostalCode
,i.EntityTypeCd
,isnull(tr.ReasonCd, '')
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4))
,bd.YearBuilt
,ln.PROPDed + '%'
,CAST(bd.BldgNumber AS VARCHAR(255))
,CONVERT(INT,REPLACE(bd.BuildingValue,',',''))
,CONVERT(INT,REPLACE(bd.ContentsBLimit,',',''))
,CONVERT(INT,REPLACE(bd.ContentsCLimit,',',''))
,CONVERT(INT,REPLACE(bd.TIBLimit,',',''))
,CONVERT(INT,REPLACE(bd.BILimit,',',''))
,CONVERT(INT,REPLACE(bd.EDPLimit,',',''))
UNION
SELECT distinct (SELECT DATEADD(DAY,-1,DATEADD(MONTH,DATEDIFF(MONTH,0,MAX(GreatestDate)) + 1, 0))
FROM
(VALUES (max(th.TransactionEffectiveDt)),(max(bp.EffectiveDt)),(max(th.TransactionDt))) AS Value(GreatestDate)) AS BookDate
,th.Transactioncd TransactionType
,bp.PolicyNumber PolicyNumber
,cast(bp.EffectiveDt AS DATE) EffectiveDate
,max(cast(th.TransactionEffectiveDt AS DATE)) TransactionEffectiveDate
,NULL
,th.TransactionNumber TransactionNumber
,cast(bp.ExpirationDt AS DATE) ExpirationDate
,replace(UPPER(ni.IndexName), ',', '') InsuredName
,replace(isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), ''), ',', '') InsuredStreetAddress
,UPPER(ad.City) InsuredCity
,UPPER(ad.StateProvCd) InsuredState
,ad.PostalCode InsuredZipCode
,i.EntityTypeCd InsuredType
,isnull(tr.ReasonCd, '') ReasonCode
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4)) ProrateFactor
,isnull(cast(th.writtenpremiumamt as int), '0') APRP
,isnull(cast(th.inforcepremiumamt as int), '0') AnnualPremium
,CONVERT(INT,REPLACE(REPLACE(REPLACE(ln.DWELLLimit, '.00', ''), '$', ''),',','')) AggreLimit
,'0'
,ln.PROPDed +'%' [% loss ded EQ]
,CASE
WHEN BD.bldgnumber > 0
THEN '0' END as bldgnumber
,'0'
,'0'
,'0'
,'0'
,'0'
,'0'
FROM java.basicpolicy bp
INNER JOIN java.nameinfo ni ON ni.SystemId = bp.SystemId
AND ni.CMMContainer = bp.CMMContainer
INNER JOIN java.line ln ON ln.CMMContainer = bp.CMMContainer
AND bp.SystemId = ln.SystemId
INNER JOIN java.building bd ON bd.CMMContainer = bp.CMMContainer
AND bd.SystemId = bp.SystemId
INNER JOIN java.addr ad ON ad.CMMContainer = ni.CMMContainer
AND bp.SystemId = ad.SystemId
AND ad.AddrTypeCd = 'InsuredMailingAddr'
INNER JOIN java.transactionhistory th ON th.CMMContainer = bp.CMMContainer
AND th.SystemId = bp.SystemId
LEFT JOIN java.transactionreason tr ON tr.CMMContainer = bp.CMMContainer
AND TR.SystemId = bp.SystemId
AND TR.ParentId = th.ID
INNER JOIN java.insured i ON i.CMMContainer = bp.CMMContainer
AND i.SystemId = bp.SystemId
WHERE bp.CMMContainer = 'policy'
AND ni.NameTypeCd = 'INSUREDNAME'
AND (
th.TransactionCd IN (
'new business'
,'endorsement'
,'cancellation'
,'rewrite-new'
)
OR (
th.WrittenPremiumAmt IS NOT NULL
AND th.WrittenPremiumAmt <> 0
AND th.TransactionCd IN ('reinstatement')
)
)
AND bp.CarrierCd = 'ENIC'
GROUP BY
th.Transactioncd
,bp.PolicyNumber
,cast(bp.EffectiveDt AS DATE)
,cast(th.TransactionEffectiveDt AS DATE)
,th.TransactionNumber
,cast(bp.ExpirationDt AS DATE)
,UPPER(ni.IndexName)
,(isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), ''))
,UPPER(ad.City)
,UPPER(ad.StateProvCd)
,ad.PostalCode
,i.EntityTypeCd
,isnull(tr.ReasonCd, '')
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4))
,isnull(cast(th.writtenpremiumamt as int), '0')
,isnull(cast(th.inforcepremiumamt as int), '0')
,CONVERT(INT,REPLACE(REPLACE(REPLACE(ln.DWELLLimit, '.00', ''), '$', ''),',',''))
,ln.PROPDed +'%'
,CASE
WHEN BD.bldgnumber > 0
THEN '0' END
ORDER BY PolicyNumber
,transactionnumber
,bldgnumber
,BOOKDATE
I get the following results:
enter image description here
Notice how there are three 1's and three 2's but only two 3's? That's because in my union, the 3 doesn't exist. Only on my top query does. What I want to do is to select everything where only it exists in my union. So for this instance, since 3 doesn't exist in my union, I want to omit it from my results. I tried doing EXISTS and IN but still not getting what I want. Been stuck on this.

Try this approach
;WITH cte
AS (SELECT 1 AS fst_indicator, -- To identify the records from first query
NULL as scd_indicator,
TransactionNumber,..
FROM First_Query
UNION ALL -- Change it to UNION if you really want to remove duplicates
SELECT NULL AS fst_indicator,
1 as scd_indicator,-- To identify the records from second query
TransactionNumber,..
FROM Second_Query),
cte1
AS (SELECT TransactionNumber
FROM cte
GROUP BY TransactionNumber
HAVING Sum(fst_indicator) >= 1 -- to make sure TransactionNumber is present in first query
AND Sum(scd_indicator) >= 1 -- to make sure TransactionNumber is present in second query
)
SELECT *
FROM cte c
WHERE EXISTS (SELECT 1
FROM cte1 c1
WHERE c.TransactionNumber = c1.TransactionNumber)

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.

Query tuning in SQL Server

My query is taking too much time to execute. I am using five views in left join, and I am trying to optimize the query. I am trying to remove some subquery into left join in from clause. Is it the right method to optimize because already five left joins there are? Please suggest.
How can I optimize and rewrite?
Orginal query
SELECT DISTINCT
TP.F_PRODUCT AS ID,
TP.F_PRODUCT_NAME AS [NAME],
(SELECT MS.F_MSDSTYPE_DESC FROM T_MSDSTYPES MS WHERE MS.F_MSDSTYPE = TP.F_SUBFORMAT AND MS.F_FORMAT = TP.F_FORMAT) AS SFMT,
(SELECT TL.F_LANGUAGE_NAME FROM T_LANGUAGES TL WHERE TL.F_LANGUAGE = TP.F_LANGUAGE) AS LANG,
TP.F_LANGUAGE AS LANGCODE,
TP.F_SUBFORMAT AS SFMTCODE,
TP.F_PLANT AS PLANTCODE,
TP.F_FORMAT AS FMTCODE,
CONVERT(VARCHAR,TP.F_DATE_REVISED,120) AS RDATE,
CASE
WHEN NOT(REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUMBERS,'¿',' '))),' ','; ') IS NULL OR REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUMBERS,'¿',' '))),' ','; ') = '') THEN REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUMBERS,'¿',' '))),' ','; ') ELSE REPLACE(LTRIM(RTRIM(REPLACE(CASN.F_DATA,'¿',' '))),' ','; ')
END AS CASNUM ,
TP.F_CUSTOM1 AS cus1,
TP.F_CUSTOM2 AS cus2,
(SELECT TC.F_COUNTRY_NAME FROM T_COUNTRIES TC WHERE TC.F_COUNTRY_CODE = TP.F_CUSTOM5) AS cus5,
MAN.F_PHRASE AS MANU,
CASE
WHEN NOT(TP.F_CUSTOM3 IS NULL OR TP.F_CUSTOM3 = '') THEN TP.F_CUSTOM3 ELSE ''
END + ' ' +
CASE
WHEN NOT(SYN.F_DATA IS NULL OR SYN.F_DATA = '') THEN SYN.F_DATA ELSE ''
END AS SYN,
IC.F_DATA AS ICO,
'SDS - ' + (SELECT TL.F_LANGUAGE_NAME FROM T_LANGUAGES TL WHERE TL.F_LANGUAGE = TP.F_LANGUAGE) + ' - PDF' AS DOC,
'' AS COVER,
CAST(TP.F_GUID AS VARCHAR(36)) + '_PDF' AS [GUID],
'PDF' AS SDS
FROM
T_PDF_MSDS TP
LEFT JOIN
T_MSDSTYPES MS ON MS.F_MSDSTYPE = TP.F_SUBFORMAT
AND MS.F_FORMAT = TP.F_FORMAT
LEFT JOIN
T_LANGUAGES TL ON TL.F_LANGUAGE = TP.F_LANGUAGE
LEFT JOIN
V_PROD_ALIAS_SYN SYN ON TP.F_PRODUCT = SYN.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_SITE SIT ON TP.F_PRODUCT = SIT.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_ICO IC ON TP.F_PRODUCT = IC.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_MANU MAN ON TP.F_PRODUCT = MAN.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_CASN CASN ON TP.F_PRODUCT = CASN.F_PRODUCT
WHERE
(TP.F_CUSTOM5 IS NULL OR TP.F_CUSTOM5 = '')
AND (TP.F_SUBFORMAT IN (SELECT ITEM FROM SPLIT_NEW('EGHS,VCH,VJP,EGHS,VFR,VDE,VIR,AGHS,VUS,VCA,VCH,VJP',',')))
AND (TP.F_DATE_REVISED BETWEEN '2018-07-16 15:04:31' AND '2018-07-18 21:51:45')
AND TP.F_AUTHORIZED IN (1,3)
i removed the sub query(SFMT,LANG COLUMN NAMES) by using left join like this.
SELECT DISTINCT TP.F_PRODUCT AS ID,
TP.F_PRODUCT_NAME AS [NAME],
MS.F_MSDSTYPE_DESC AS SFMT,
TL.F_LANGUAGE_NAME AS LANG,
TP.F_LANGUAGE AS LANGCODE,
TP.F_SUBFORMAT AS SFMTCODE,
TP.F_PLANT AS PLANTCODE,
TP.F_FORMAT AS FMTCODE,
CONVERT(VARCHAR,TP.F_DATE_REVISED,120) AS RDATE,
CASE
WHEN NOT(REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUMBERS,'¿',' '))),' ','; ') IS NULL OR REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUMBERS,'¿',' '))),' ','; ') = '') THEN REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUMBERS,'¿',' '))),' ','; ') ELSE REPLACE(LTRIM(RTRIM(REPLACE(CASN.F_DATA,'¿',' '))),' ','; ')
END AS CASNUM ,
TP.F_CUSTOM1 AS cus1,
TP.F_CUSTOM2 AS cus2,
(SELECT TC.F_COUNTRY_NAME FROM T_COUNTRIES TC WHERE TC.F_COUNTRY_CODE = TP.F_CUSTOM5) AS cus5,
MAN.F_PHRASE AS MANU,
CASE
WHEN NOT(TP.F_CUSTOM3 IS NULL OR TP.F_CUSTOM3 = '') THEN TP.F_CUSTOM3 ELSE ''
END + ' ' +
CASE
WHEN NOT(SYN.F_DATA IS NULL OR SYN.F_DATA = '') THEN SYN.F_DATA ELSE ''
END AS SYN,
IC.F_DATA AS ICO,
'SDS - ' + (SELECT TL.F_LANGUAGE_NAME FROM T_LANGUAGES TL WHERE TL.F_LANGUAGE = TP.F_LANGUAGE) + ' - PDF' AS DOC,
'' AS COVER,
CAST(TP.F_GUID AS VARCHAR(36)) + '_PDF' AS [GUID],
'PDF' AS SDS
FROM T_PDF_MSDS TP
LEFT JOIN T_MSDSTYPES MS ON
MS.F_MSDSTYPE = TP.F_SUBFORMAT
AND MS.F_FORMAT = TP.F_FORMAT
LEFT JOIN T_LANGUAGES TL ON
TL.F_LANGUAGE = TP.F_LANGUAGE
LEFT JOIN V_PROD_ALIAS_SYN SYN
ON TP.F_PRODUCT = SYN.F_PRODUCT
LEFT JOIN V_PROD_ALIAS_SITE SIT
ON TP.F_PRODUCT = SIT.F_PRODUCT
LEFT JOIN V_PROD_ALIAS_ICO IC
ON TP.F_PRODUCT = IC.F_PRODUCT
LEFT JOIN V_PROD_ALIAS_MANU MAN
ON TP.F_PRODUCT = MAN.F_PRODUCT
LEFT JOIN V_PROD_ALIAS_CASN CASN
ON TP.F_PRODUCT = CASN.F_PRODUCT WHERE (TP.F_CUSTOM5 IS NULL OR TP.F_CUSTOM5 = '') AND (TP.F_SUBFORMAT IN (SELECT ITEM FROM SPLIT_NEW('EGHS,VCH,VJP,EGHS,VFR,VDE,VIR,AGHS,VUS,VCA,VCH,VJP',','))) AND (TP.F_DATE_REVISED BETWEEN '2018-07-16 15:04:31' AND '2018-07-18 21:51:45') AND TP.F_AUTHORIZED IN (1,3)
will it improve performance?

Column invalid in select list because it is contained in either an aggregate function or the GROUP BY clause

I know similar questions have been covered for this topic, I've looked through the answers but I just can't work out how to apply to this query unfortunately.
I know that adding 'pe.short_name' to GROUP BY isn't the best way to handle this either.
Any suggestions very much appreciated..
Column 'pe.short_name' invalid in select list because it is contained
in either an aggregate function or the GROUP BY clause.`
SELECT CASE
WHEN SUBSTRING(s.description, 13, 1) = '.'
THEN LEFT(s.description, 17)
ELSE LEFT(s.description, 12)
END WBSCode
,pe.short_name
,pn.description ProjectName
,(
SELECT description
FROM structure
WHERE structure_code = pe.code346
) ActivePortfolio
,CASE
WHEN ast.Description = 'WAIO'
THEN anc.Description
ELSE site.Description
END SiteFunction
,CASE
WHEN SUBSTRING(jv.description, 5, 1) = ' '
THEN LEFT(jv.description, 4)
WHEN SUBSTRING(jv.description, 7, 1) = ' '
THEN LEFT(jv.description, 6)
ELSE jv.Description
END AS JointVenture
,(
SELECT description
FROM structure
WHERE structure_code = pe.code79
) AssetClassification
,(
SELECT description
FROM structure
WHERE structure_code = pe.code390
) InvestmentSize
,(
SELECT RIGHT(import_code, 6)
FROM structure
WHERE structure_code = pe.code79
) AssetClassCode
,CAST(p.period_start AS DATE) Period_Start
,SUM(CASE
WHEN be.currency_code = 'AUD'
AND #Currency = 'AUD'
THEN be.amount
WHEN be.currency_code = 'USD'
AND #Currency = 'USD'
THEN be.amount
WHEN be.currency_code = 'AUD'
AND #Currency = 'USD'
THEN be.amount * ip.pfn_exch_rate_on_date(p.period_start, be.currency_code)
WHEN be.currency_code = 'USD'
AND #Currency = 'AUD'
THEN be.amount * (ip.pfn_exch_rate_on_date(p.period_start, be.currency_code) / ip.pfn_exch_rate_on_date(p.period_start, 'AUD'))
END) Amount
FROM fm_budget_entry be
JOIN fm_period p ON be.period_id = p.period_id
JOIN fm_budget_line bl ON be.line_id = bl.line_id
AND bl.version_id = #FinancialVersion
JOIN fm_budget_line_attrib la ON la.line_id = bl.line_id
AND la.line_attrib_code = 'Wbs138'
JOIN structure s ON la.line_attrib_value = s.structure_code
JOIN fm_account fa ON bl.account_code = fa.account_code
JOIN planning_entity pe ON pe.planning_code = bl.structure_code
JOIN structure ast ON ast.structure_code = pe.code713
AND ast.Description IN (#Assets)
JOIN structure pn ON pn.structure_code = pe.planning_code
LEFT JOIN structure site ON site.structure_code = pe.code37
LEFT JOIN structure_tree tr ON tr.dsc_code = pe.planning_code
AND tr.anc_Depth = 5
LEFT JOIN structure anc ON anc.structure_code = tr.anc_code
LEFT JOIN fm_version v ON v.version_id = bl.version_id
LEFT JOIN structure pc ON pc.structure_code = s.father_code
LEFT JOIN structure jv ON pc.father_code = jv.structure_code
AND jv.father_code <> 'Wbs138Root'
WHERE fa.account_type_code IN (#FundingType)
AND p.period_id BETWEEN #StartDate
AND #FinishDate
AND pe.code346 IN (#ActivePortfolio)
GROUP BY CASE
WHEN SUBSTRING(s.description, 13, 1) = '.'
THEN LEFT(s.description, 17)
ELSE LEFT(s.description, 12)
END
,pn.description
,pe.code346
,CASE
WHEN ast.Description = 'WAIO'
THEN anc.Description
ELSE site.Description
END
,CASE
WHEN SUBSTRING(jv.description, 5, 1) = ' '
THEN LEFT(jv.description, 4)
WHEN SUBSTRING(jv.description, 7, 1) = ' '
THEN LEFT(jv.description, 6)
ELSE jv.Description
END
,pe.code79
,pe.code390
,CAST(p.period_start AS DATE)
ORDER BY 1
,CAST(p.period_start AS DATE)
Try this:
SELECT CASE
WHEN SUBSTRING(s.description, 13, 1) = '.'
THEN LEFT(s.description, 17)
ELSE LEFT(s.description, 12)
END WBSCode
,pe.short_name
,pn.description ProjectName
,(
SELECT description
FROM structure
WHERE structure_code = pe.code346
) ActivePortfolio
,CASE
WHEN ast.Description = 'WAIO'
THEN anc.Description
ELSE site.Description
END SiteFunction
,CASE
WHEN SUBSTRING(jv.description, 5, 1) = ' '
THEN LEFT(jv.description, 4)
WHEN SUBSTRING(jv.description, 7, 1) = ' '
THEN LEFT(jv.description, 6)
ELSE jv.Description
END AS JointVenture
,(
SELECT description
FROM structure
WHERE structure_code = pe.code79
) AssetClassification
,(
SELECT description
FROM structure
WHERE structure_code = pe.code390
) InvestmentSize
,(
SELECT RIGHT(import_code, 6)
FROM structure
WHERE structure_code = pe.code79
) AssetClassCode
,CAST(p.period_start AS DATE) Period_Start
,SUM(CASE
WHEN be.currency_code = 'AUD'
AND #Currency = 'AUD'
THEN be.amount
WHEN be.currency_code = 'USD'
AND #Currency = 'USD'
THEN be.amount
WHEN be.currency_code = 'AUD'
AND #Currency = 'USD'
THEN be.amount * ip.pfn_exch_rate_on_date(p.period_start, be.currency_code)
WHEN be.currency_code = 'USD'
AND #Currency = 'AUD'
THEN be.amount * (ip.pfn_exch_rate_on_date(p.period_start, be.currency_code) / ip.pfn_exch_rate_on_date(p.period_start, 'AUD'))
END) Amount
FROM fm_budget_entry be
JOIN fm_period p ON be.period_id = p.period_id
JOIN fm_budget_line bl ON be.line_id = bl.line_id
AND bl.version_id = #FinancialVersion
JOIN fm_budget_line_attrib la ON la.line_id = bl.line_id
AND la.line_attrib_code = 'Wbs138'
JOIN structure s ON la.line_attrib_value = s.structure_code
JOIN fm_account fa ON bl.account_code = fa.account_code
JOIN planning_entity pe ON pe.planning_code = bl.structure_code
JOIN structure ast ON ast.structure_code = pe.code713
AND ast.Description IN (#Assets)
JOIN structure pn ON pn.structure_code = pe.planning_code
LEFT JOIN structure site ON site.structure_code = pe.code37
LEFT JOIN structure_tree tr ON tr.dsc_code = pe.planning_code
AND tr.anc_Depth = 5
LEFT JOIN structure anc ON anc.structure_code = tr.anc_code
LEFT JOIN fm_version v ON v.version_id = bl.version_id
LEFT JOIN structure pc ON pc.structure_code = s.father_code
LEFT JOIN structure jv ON pc.father_code = jv.structure_code
AND jv.father_code <> 'Wbs138Root'
WHERE fa.account_type_code IN (#FundingType)
AND p.period_id BETWEEN #StartDate
AND #FinishDate
AND pe.code346 IN (#ActivePortfolio)
GROUP BY CASE
WHEN SUBSTRING(s.description, 13, 1) = '.'
THEN LEFT(s.description, 17)
ELSE LEFT(s.description, 12)
END
,pe.short_name
,pn.description
,pe.code346
,CASE
WHEN ast.Description = 'WAIO'
THEN anc.Description
ELSE site.Description
END
,CASE
WHEN SUBSTRING(jv.description, 5, 1) = ' '
THEN LEFT(jv.description, 4)
WHEN SUBSTRING(jv.description, 7, 1) = ' '
THEN LEFT(jv.description, 6)
ELSE jv.Description
END
,pe.code79
,pe.code390
,CAST(p.period_start AS DATE)
ORDER BY 1
,CAST(p.period_start AS DATE)

Showing a row that doesn't exist

I have a select that fetches some data for me.
I'm trying to make a query that shows me that data but if it doesn't exist it will show me the first 5 columns with data that I provided. Here is the query
DECLARE #miesiac INT = 1
DECLARE #opis VARCHAR(30) = '';
WITH cte
AS ( SELECT DISTINCT
ROW_NUMBER() OVER ( PARTITION BY emp_name,
doc_documentdate ORDER BY doc_documentdate ) s
,emp_name Kod
,emp_id id
,Emp_Surname Nazwisko
,Emp_FirstName Imie
,ISNULL(CONVERT(VARCHAR(10), Doc_DocumentDate, 120), '') Data
,CASE WHEN doc_documentdate = ttc_date
AND ttc_isholiday = 0 THEN 'S'
WHEN doc_documentdate = ttc_date
AND ttc_isholiday = 6
OR ttc_isholiday = 7
OR ELM_DecimalColumn1 = 0 THEN 'W'
WHEN ELM_DecimalColumn1 IS NULL THEN 'w'
ELSE 'P'
END Typdnia
,ISNULL(CONVERT(VARCHAR(8), elm_datecolumn1, 108),
'00:00:00') GodzOd
,ISNULL(CONVERT(VARCHAR(8), elm_datecolumn2, 108),
'00:00:00') GodzDo
,CASE WHEN ELM_decimalcolumn1 > 0
THEN 'praca podstawowa'
ELSE 'brak'
END Strefa
,#opis Opis
,ISNULL(emp_shortstringcolumn2, 'brak') Wydzial
,ISNULL(ELM_ShortStringColumn5, '0') Wydzial_adres_wezla
,ISNULL(a.dic_svalue, ' brak') Projekt
,ISNULL(b.DIC_ShortStringColumn1, '1') Projekt_adres_wezla
FROM Employees
LEFT JOIN elements ON emp_id = ELM_EmpID
AND ELM_FflID = 200
LEFT JOIN documents ON elm_objectid = doc_id
AND Doc_DdfID = 2
LEFT JOIN dictionaries a ON ELM_IntColumn2 = a.DIC_ID
LEFT JOIN Dictionaries b ON elm_intcolumn2 = b.DIC_ID
LEFT JOIN ttscalendar ON ttc_date = Doc_DocumentDate
RIGHT JOIN dim_timeday ON doc_documentdate = tmd_fulldatekey
)
SELECT ISNULL(cte1.kod, '') Kod
,ISNULL(cte1.nazwisko, '') Nazwisko
,ISNULL(cte1.imie, '') Imie
,ISNULL(cte1.data, '') Data
,ISNULL(cte1.TypDnia, '') Typdnia
,ISNULL(cte1.GodzOd, '00:00') W1_GodzOd
,ISNULL(cte1.godzdo, '00:00') W1_GodzDo
,ISNULL(cte1.strefa, 'brak') W1_Strefa
,ISNULL(cte1.opis, '') W1_Opis
,ISNULL(cte1.wydzial, 'brak') W1_Wydzial
,ISNULL(cte1.wydzial_adres_wezla, '0') W1_Wydzial_adres_wezla
,ISNULL(cte1.Projekt, 'brak') W1_Projekt
,ISNULL(cte1.Projekt_adres_wezla, '1') W1_Projekt_adres_wezla
,ISNULL(cte2.GodzOd, '') W2_GodzOd
,ISNULL(cte2.godzdo, '') W2_GodzDo
,ISNULL(cte2.strefa, '') W2_Strefa
,ISNULL(cte2.opis, '') W2_Opis
,ISNULL(cte2.wydzial, '') W2_Wydzial
,ISNULL(cte2.wydzial_adres_wezla, '') W2_Wydzial_adres_wezla
,ISNULL(cte2.Projekt, '') W2_Projekt
,ISNULL(cte2.Projekt_adres_wezla, '') W2_Projekt_adres_wezla
,ISNULL(cte3.GodzOd, '') W3_GodzOd
,ISNULL(cte3.godzdo, '') W3_GodzDo
,ISNULL(cte3.strefa, '') W3_Strefa
,ISNULL(cte3.opis, '') W3_Opis
,ISNULL(cte3.wydzial, '') W3_Wydzial
,ISNULL(cte3.wydzial_adres_wezla, '') W3_Wydzial_adres_wezla
,ISNULL(cte3.Projekt, '') W3_Projekt
,ISNULL(cte3.Projekt_adres_wezla, '') W3_Projekt_adres_wezla
,ISNULL(cte4.GodzOd, '') W4_GodzOd
,ISNULL(cte4.godzdo, '') W4_GodzDo
,ISNULL(cte4.strefa, '') W4_Strefa
,ISNULL(cte4.opis, '') W4_Opis
,ISNULL(cte4.wydzial, '') W4_Wydzial
,ISNULL(cte4.wydzial_adres_wezla, '') W4_Wydzial_adres_wezla
,ISNULL(cte4.Projekt, '') W4_Projekt
,ISNULL(cte4.Projekt_adres_wezla, '') W4_Projekt_adres_wezla
,ISNULL(cte5.GodzOd, '') W5_GodzOd
,ISNULL(cte5.godzdo, '') W5_GodzDo
,ISNULL(cte5.strefa, '') W5_Strefa
,ISNULL(cte5.opis, '') W5_Opis
,ISNULL(cte5.wydzial, '') W5_Wydzial
,ISNULL(cte5.wydzial_adres_wezla, '') W5_Wydzial_adres_wezla
,ISNULL(cte5.Projekt, '') W5_Projekt
,ISNULL(cte5.Projekt_adres_wezla, '') W5_Projekt_adres_wezla
,ISNULL(cte6.GodzOd, '') W6_GodzOd
,ISNULL(cte6.godzdo, '') W6_GodzDo
,ISNULL(cte6.strefa, '') W6_Strefa
,ISNULL(cte6.opis, '') W6_Opis
,ISNULL(cte6.wydzial, '') W6_Wydzial
,ISNULL(cte6.wydzial_adres_wezla, '') W6_Wydzial_adres_wezla
,ISNULL(cte6.Projekt, '') W6_Projekt
,ISNULL(cte6.Projekt_adres_wezla, '') W6_Projekt_adres_wezla
FROM cte cte1
LEFT JOIN cte cte2 ON cte1.Kod = cte2.kod
AND cte1.data = cte2.data
AND cte2.s = 2
LEFT JOIN cte cte3 ON cte2.Kod = cte3.kod
AND cte2.data = cte3.data
AND cte3.s = 3
LEFT JOIN cte cte4 ON cte3.Kod = cte4.kod
AND cte3.data = cte4.data
AND cte4.s = 4
LEFT JOIN cte cte5 ON cte4.Kod = cte5.kod
AND cte4.data = cte5.data
AND cte5.s = 5
LEFT JOIN cte cte6 ON cte5.Kod = cte6.kod
AND cte5.data = cte6.data
AND cte6.s = 6
WHERE cte1.s = 1
AND MONTH(cte1.data) = #Miesiac
AND cte1.id = 7
ORDER BY cte1.data
,cte1.kod
Here is the data
ANJO_141 ANTONKIEWICZ JOLANTA 2016-01-22 S 00:00:00 00:00:00 brak NF 1.8 brak 1
ANJO_141 ANTONKIEWICZ JOLANTA 2016-01-23 W 07:00:00 12:00:00 praca podstawowa NF 1.8 brak 1
ANJO_141 ANTONKIEWICZ JOLANTA 2016-01-27 P 07:00:00 15:00:00 praca podstawowa NF 1.8 brak 1
ANJO_141 ANTONKIEWICZ JOLANTA 2016-01-28 W 00:00:00 00:00:00 brak NF 1.8 brak 1

Store procedure for a select statement which should take input

Can anyone please help me with the store procedure for the following
select statement which should take an input of completeddatekey which
is at the bottom of the select statement
CompletedDateKey is filled with a key in this code but I need a store procedure that should take an input of completeddatekey
SELECT FactId
,UserType
,wr.WorkRequestId
,wr.XerisUserKey
,xu.CsuserUserID UserId
,u.fname UserFName
,u.lname UserLName
,b.PatientId
,p.firstname PatFName
,p.lastname PatLName
,GroupId
,HospiceGroupKey GroupKey
,WR.ContactKey
,C.ContactId
,C.FirstName
,C.LastName
,Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )) Start_dtm
,Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay )) End_dtm
,DATEDIFF(s,
Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay)),
Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))) WRDuration
,(Convert(Decimal(18,3), DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )), Convert(datetime,(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))))) * (Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration
,CallBackNumber
,WorkRequestType
,B.LineItemCount
,ArchiveLocation
,Processed
,ArchiveQueueType
,TQA
,Exclude
,CallId
FROM bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
left outer join ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy as h with (nolock) on b.groupid = h.group_id
WHERE CompletedDateKey = '20140131'
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null
Its really simple. Just create procedure like below
create procedure MyProc(
#CompletedDateKey varchar(20) )
as
Begin
SELECT FactId
,UserType
,wr.WorkRequestId
,wr.XerisUserKey
,xu.CsuserUserID UserId
,u.fname UserFName
,u.lname UserLName
,b.PatientId
,p.firstname PatFName
,p.lastname PatLName
,GroupId
,HospiceGroupKey GroupKey
,WR.ContactKey
,C.ContactId
,C.FirstName
,C.LastName
,Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )) Start_dtm
,Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay )) End_dtm
,DATEDIFF(s,
Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay)),
Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))) WRDuration
,(Convert(Decimal(18,3), DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )), Convert(datetime,(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))))) * (Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration
,CallBackNumber
,WorkRequestType
,B.LineItemCount
,ArchiveLocation
,Processed
,ArchiveQueueType
,TQA
,Exclude
,CallId
FROM bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
left outer join ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy as h with (nolock) on b.groupid = h.group_id
WHERE CompletedDateKey = #CompletedDateKey
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null
End
Execute it like
Execute MyProc '20140131'