WHERE returning entire table - sql

Question: How do I ignore WHERE param if value = '0' or NULL
One of the columns returned is showing 0 which is causing problems in my query.
The problem I am having is in the p.author value. Sometimes it matches up with a pe.system_id, but sometimes it is 0 or NULL. If p.author is 0. If I comment the and param out, then it returns a row for each entry in docsadm.people pe1 or nothing because no entry = 0
SELECT
p.docnumber, p.docname, p.abstract, d.type_id, a.application,
pe1.full_name as 'Author', pe.full_name as 'Registered by',
convert(varchar(10), p.pif_letter_date + 0.4166666,111) as 'Date written',
convert(varchar(10), p.creation_date + 0.4166666,111) as 'Registered on',
convert(varchar(10), p.last_edit_date + 0.4166666,111) as 'Last edit date',
f.pd_filept_no, f.pd_file_name, f.pd_title, sm.pif_marking, s.pd_section_code,
p.status as 'Availability', p.related, p.kmc_old_docno
FROM
docsadm.profile p, docsadm.pd_file_part f, docsadm.people pe,
docsadm.people pe1, docsadm.apps a, docsadm.documenttypes d,
docsadm.pif_sec_mark sm, docsadm.pd_section s
WHERE
p.DOCNUMBER IN ('5451326')
AND p.pd_file_part = f.system_id
AND p.typist = pe.system_id
AND p.author = pe1.system_id --Problem Line
AND p.application = a.system_id
AND p.documenttype = d.system_id
AND f.kmc_ptto_sec_mark = sm.system_id
AND f.pd_pttosec_link = s.system_id
AND p.item_type IN ('D','E','M','F')
ORDER BY
5, 4, 1

There are a number of ways but the way I prefer is to use the JOIN .. ON syntax and make tables with optional data part of a LEFT OUTER JOIN (LEFT JOIN).
SELECT p.docnumber,
p.docname,
p.abstract,
d.type_id,
a.application,
pe1.full_name as 'Author',
pe.full_name as 'Registered by',
convert(varchar(10), p.pif_letter_date + 0.4166666,111) as 'Date written',
convert(varchar(10), p.creation_date + 0.4166666,111) as 'Registered on',
convert(varchar(10), p.last_edit_date + 0.4166666,111) as 'Last edit date',
f.pd_filept_no,
f.pd_file_name,
f.pd_title,
sm.pif_marking,
s.pd_section_code,
p.status as 'Availability',
p.related,
p.kmc_old_docno
FROM docsadm.profile p
JOIN docsadm.pd_file_part f
ON p.pd_file_part = f.system_id
JOIN docsadm.people pe
ON p.typist = pe.system_id
JOIN docsadm.apps a
ON p.application = a.system_id
JOIN docsadm.documenttypes d
ON p.documenttype = d.system_id
JOIN docsadm.pif_sec_mark sm
ON f.kmc_ptto_sec_mark = sm.system_id
JOIN docsadm.pd_section s
ON f.pd_pttosec_link = s.system_id
LEFT
JOIN docsadm.people pe1
ON p.author = pe1.system_id --Problem Line
WHERE p.DOCNUMBER in ('5451326')
and p.item_type in ('D','E','M','F')
ORDER by 5, 4, 1

...
and ( (p.author is null) or (p.author='0') or (p.author=pe1.system_id) )
...
...work?
If p.author is null or p.author=0 it will turn that "and ..." into "and true"

Related

Microsoft SQL Server: where logic - Column stored as an integer but represents a date in my table

I'm running into an issue with my Where clause;
AND CAST(h.chinto as DATETIME) >= DATEADD(DAY, -7, GetDate())
chinto is stored as an integer in the format YYYYMMDD and represents a date. Im trying to write a where clause to sort my results based on the last 30 days ect.
Ive tried try_convert to change the data type to a date but I cant seem to get it right. Always running into an the error: Arithmetic overflow error converting expression to data type datetime.
SELECT top 100
[ClaimNumber] = MAX(RIGHT('00000000' + convert(varchar(8),h.chclno),8) + RIGHT('00' + convert(varchar(8),h.chwkno),2)),
[EmployeeSSN] = RTRIM(MAX(RIGHT('000000000' + CONVERT(VARCHAR(9),m.edssno),9))),
[EmployeeID] = RTRIM(MAX(ee.edmemb)),
[EmployeeLastName] = RTRIM(MAX(m.edlnmk)),
[EmployeeFirstName] = RTRIM(MAX(m.edfnam)),
[PatientSSN] = RTRIM(MAX(RIGHT('000000000' + CONVERT(VARCHAR(9),e.eessno),9))),
[PatientDOB] = RTRIM(MAX(m.edbrdt)),
[PatientGender] = RTRIM(MAX(m.edsexx)),
-- m.edbrdt as 'PatientDOB',
--m.edsexx as 'PatientGender',
[FirstDateOfService] = MAX(left(convert(char(8),h.chinfr),4) + '-' + substring(convert(char(8),h.chinfr),5,2) + '-' + right(convert(char(8),h.chinfr),2) ),
[LastDateOfService] = MAX(left(convert(char(8),h.chinto),4) + '-' + substring(convert(char(8),h.chinto),5,2) + '-' + right(convert(char(8),h.chinto),2) ),
[ProviderName] = MAX(ps.pmname),
[ProviderAddress1] = MAX(CASE WHEN sn.npinpi = nps.NPI THEN RTRIM(nps.Prov_First_Line_Business_Practice_Location_Address) ELSE RTRIM(ps.pmadr1) COLLATE SQL_Latin1_General_Cp1_CS_AS END ),
[ProviderAddress2] = MAX(CASE WHEN sn.npinpi = nps.NPI THEN RTRIM(ISNULL(nps.Prov_Second_Line_Business_Practice_Location_Address,'')) ELSE RTRIM(ps.pmadr2) COLLATE SQL_Latin1_General_Cp1_CS_AS END ),
[ProviderCity] = MAX(CASE WHEN sn.npinpi = nps.NPI THEN RTRIM(ISNULL(nps.Prov_Business_Mailing_Address_City_Name,'')) ELSE RTRIM(ps.pmadr2) COLLATE SQL_Latin1_General_Cp1_CS_AS END ),
[ProviderState] = MAX(CASE WHEN sn.npinpi = nps.NPI THEN RTRIM(nps.Prov_Business_Practice_Location_Address_ST_Name) ELSE RTRIM(ps.pmstat) COLLATE SQL_Latin1_General_Cp1_CS_AS END ),
[ProviderZIP] = MAX(CASE WHEN sn.npinpi = nps.NPI THEN LEFT(nps.Prov_Business_Practice_Location_Address_Postal_CD,5) ELSE LEFT(ps.pmzpcd,5) COLLATE SQL_Latin1_General_Cp1_CS_AS END ),
--[ProviderTIN] ,
--[ProviderTINSuffix] ?,
[DiagnosisCode1] = RTRIM(MAX(h.chdgcd)),
[DiagnosisCode2] = RTRIM(MAX(ISNULL(h.chadgc_1,''))),
[DiagnosisCode3] = RTRIM(MAX(ISNULL(h.chadgc_2,''))),
[DiagnosisCode4] = RTRIM(MAX(ISNULL(h.chadgc_3,''))),
[DiagnosisCode5] = RTRIM(MAX(ISNULL(h.chadgc_4,''))),
[DiagnosisCode6] = RTRIM(MAX(ISNULL(h.chadgc_5,''))),
[DiagnosisCode7] = RTRIM(MAX(ISNULL(h.chadgc_6,''))),
[DiagnosisCode8] = RTRIM(MAX(ISNULL(h.chadgc_7,''))),
[DiagnosisCode9] = RTRIM(MAX(ISNULL(h.chadgc_8,''))),
--[ProcedureCode1?] = RTRIM(MAX(d.cdproc)) ---> clmdet missing prod code(s)/date(s) joined ACO.dbo.clmubf p
[ProcedureCode1] = RTRIM(MAX(ISNULL(p.cwprcd_1, ''))),
[ProcedureDate1] = RTRIM(MAX(ISNULL(p.cwprdt_1, ''))),
[ProcedureCode2] = RTRIM(MAX(ISNULL(p.cwprcd_2, ''))),
[ProcedureDate2] = RTRIM(MAX(ISNULL(p.cwprdt_2, ''))),
[ProcedureCode3] = RTRIM(MAX(ISNULL(p.cwprcd_3, ''))),
[ProcedureDate3] = RTRIM(MAX(ISNULL(p.cwprdt_3, ''))),
[ProcedureCode4] = RTRIM(MAX(ISNULL(p.cwprcd_4, ''))),
[ProcedureDate4] = RTRIM(MAX(ISNULL(p.cwprdt_4, ''))),
[ProcedureCode5] = RTRIM(MAX(ISNULL(p.cwprcd_5, ''))),
[ProcedureDate5] = RTRIM(MAX(ISNULL(p.cwprdt_5, ''))),
[ProcedureCode6] = RTRIM(MAX(ISNULL(p.cwprcd_6, ''))),
[ProcedureDate6] = RTRIM(MAX(ISNULL(p.cwprdt_6, ''))),
[TotalCharge] = SUM(d.cdtchg),
--[TotalCharge] = SUM(c.dichga?) --> drghis table missing from ACO.dbo, has all the info I need (clmdet d missing columns)
--[AllowableCharge] = ?,
[TotalIneligible] = SUM(d.cdinea),
--[TotalEligible] =,
[TotalDiscount] = SUM(d.cddisc),
[TotalDeductible] = SUM(d.cddeda),
[TotalCoPay] = SUM(d.cdcopa),
[TotalCoInsurance] = SUM(d.cdleva_1)
--[TotalPaid] = SUM(d.cdcoba?)
--[ClaimType]
FROM
ACO.dbo.clmhdr h
INNER JOIN ACO.dbo.clmdet d ON h.chclno = d.cdclno AND h.chwkno = d.cdwkno
INNER JOIN ACO.dbo.elgdep m ON h.chemno = m.ednmbr AND h.chdpcd = m.eddpcd
INNER JOIN ACO.dbo.elgemp e ON m.ednmbr = e.eenmbr
INNER JOIN ACO.dbo.elgdep ee ON e.eenmbr = ee.ednmbr AND ee.eddpcd = 'e'
INNER JOIN ACO.dbo.clmubf p ON h.chclno = p.cwclno
--INNER JOIN ACO.dbo.drghis? c ON h.chclno = c.diclno
LEFT OUTER JOIN ACO.dbo.prvmst pp ON d.cdpvno = pp.pmnmbr
LEFT OUTER JOIN ACO.dbo.prvmst ps ON d.cdspno = ps.pmnmbr
LEFT OUTER JOIN ACO.dbo.prvnpi sn ON d.cdspno = sn.npinmbr
LEFT OUTER JOIN ACO.dbo.prvnpi pn ON d.cdpvno = pn.npinmbr
LEFT OUTER JOIN [RIMSReport].[dbo].[NPI] nps ON sn.npinpi = nps.NPI
LEFT OUTER JOIN [RIMSReport].[dbo].[NPI] npp ON pn.npinpi = npp.NPI
WHERE
h.chgpno = 'CTT0001'
AND CAST(h.chinto as DATETIME) >= DATEADD(DAY, -7, GetDate())
GROUP BY
h.chclno, h.chinto
--m.edsexx, m.edbrdt
Casting int to date isn't allowed, but you can cast from string instead.
Try this: select cast(cast(h.chinto as varchar(10)) as date)

Invalid column in unpivot CTE query

I am getting the error Invalid column name MERCHANDISE_AMT'. on the below CTE unpivot query. I am selecting in MERCHANDISE_AMT in both queries so I do not understand why it's coming up as invalid. What am I overlooking here? If I take MERCHANDISE_AMT out of the unpivot than it runs, but I need to use this column for unpivoting. (unpivot (value FOR col IN (MERCHANDISE_AMT, FREIGHT_AMT, SALETX_AMT)) u
;WITH CTE AS (
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 AS LINE_TYPE , A.MERCHANDISE_AMT, CASE WHEN CONVERT(CHAR(24),A.QTY_VCHR) = '0' THEN '' ELSE B.QTY_VCHR END AS INVOICE_QTY, CASE WHEN CONVERT(CHAR(24),A.UNIT_PRICE) = '0' THEN '' ELSE A.UNIT_PRICE END AS UNIT_PRICE , A.UNIT_OF_MEASURE, REPLACE(A.DESCR,'"','') AS DESCR , '' AS BLANK1, '' AS BLANK2--A.PO_ID, A.LINE_NBR,
, ''AS BLANK3, ''AS BLANK4, --A.SCHED_NBR, B.PO_DIST_LINE_NUM,
''AS BLANK5,
''AS BLANK6,''AS BLANK7,''AS BLANK777,''AS BLANK8,''AS BLANK9,''AS BLANK10,''AS BLANK11,''AS BLANK12,
F.ORACLE_ENTITY + '.' + F.ORACLE_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'
WHEN B.BUSINESS_UNIT_GL = '14000' AND H.DEPTID = '881' THEN '000'
WHEN B.BUSINESS_UNIT_GL = '14000' AND H.DEPTID = '889' THEN '950'
WHEN B.BUSINESS_UNIT_GL = '11000' AND H.DEPTID = '775' THEN '000'
WHEN B.DEPTID = '' THEN '000'
ELSE B.DEPTID END
+ '.' + B.ACCOUNT + '.' + ISNULL(G.ORACLE_PROJECT_CODE,'000000000.') + ISNULL(NULLIF(B.AFFILIATE, ''), '00000.') + '.000.' + '000000' AS SEGMENTS ,
''AS BLANK13, '2021/05/31' AS DATE1, ''AS BLANK14,''AS BLANK15,''AS BLANK16,''AS BLANK17, ''AS BLANK18, --A.SHIPTO_ID
''AS BLANK19,''AS BLANK199,''AS BLANK1999,''AS BLANK20,''AS BLANK21,''AS BLANK211,''AS BLANK22,''AS BLANK23,''AS BLANK24,''AS BLANK25,''AS BLANK26,''AS BLANK27,''AS BLANK28,''AS BLANK29,''AS BLANK30,''AS BLANK31,
''AS BLANK134,
''AS BLANK32, ''AS BLANK33, ''AS BLANK34, --A.SALETX_AMT --<--IS THIS THE RIGHT FIELD?
''AS BLANK35, ''AS BLANK36, --B.QTY_VCHR,
'N'AS BLANK37, ''AS BLANK38,''AS BLANK39,''AS BLANK40,''AS BLANK41,''AS BLANK411,''AS BLANK42, ''AS BLANK43, ''AS BLANK44,''AS BLANK45,''AS BLANK46,''AS BLANK47,''AS BLANK48,''AS BLANK49,''AS BLANK50,''AS BLANK51,''AS BLANK52,''AS BLANK53,''AS BLANK54,''AS BLANK55,''AS BLANK56,''AS BLANK57,''AS BLANK58,''AS BLANK59,''AS BLANK60,''AS BLANK61,''AS BLANK62,''AS BLANK63,''AS BLANK64,''AS BLANK65,''AS BLANK66,''AS BLANK67,''AS BLANK68,''AS BLANK69,''AS BLANK70,''AS BLANK71,''AS BLANK72,''AS BLANK73,''AS BLANK74,''AS BLANK75,''AS BLANK76,''AS BLANK77,''AS BLANK78,''AS BLANK79,''AS BLANK80,
''AS BLANK81,''AS BLANK82,''AS BLANK83,''AS BLANK84,''AS BLANK85,''AS BLANK86,''AS BLANK87,''AS BLANK88,''AS BLANK89,''AS BLANK90,''AS BLANK91,''AS BLANK92,''AS BLANK93,''AS BLANK94,''AS BLANK95,''AS BLANK96,''AS BLANK97,''AS BLANK98,''AS BLANK99,''AS BLANK100,''AS BLANK101,''AS BLANK102,''AS BLANK103,''AS BLANK104,''AS BLANK105,''AS BLANK106,''AS BLANK107,''AS BLANK108,''AS BLANK109,''AS BLANK110,''AS BLANK111,''AS BLANK112,''AS BLANK113,''AS BLANK114,''AS BLANK115,''AS BLANK116,''AS BLANK117,''AS BLANK118,''AS BLANK119,''AS BLANK120,''AS BLANK121,''AS BLANK122,''AS BLANK123,''AS BLANK124,''AS BLANK125,''AS BLANK126,''AS BLANK127,''AS BLANK128,''AS BLANK129,''AS BLANK130,''AS BLANK131,'' AS BLANK132
, C.SALETX_AMT, C.FREIGHT_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 AND D.WTHD_ENTITY = 'IRS'
LEFT OUTER JOIN PS_VCHR_LINE_WTHD DD ON DD.BUSINESS_UNIT = D.BUSINESS_UNIT AND DD.VOUCHER_ID = D.VOUCHER_ID AND DD.VOUCHER_LINE_NUM = D.VOUCHER_LINE_NUM AND DD.WTHD_ENTITY = 'PA'
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 C.ACCOUNTING_DT < '06-01-2021'
AND I.PYMNT_ID = ''
AND C.CLOSE_STATUS <> 'C'
AND C.ENTRY_STATUS <> 'X'
AND C.MATCH_STATUS_VCHR = 'M'
AND C.APPR_STATUS = 'A'
AND B.VOUCHER_ID = '00720667' )
SELECT INVOICE_ID, VOUCHER_LINE_NUM - 1 + row_number() over (PARTITION BY INVOICE_ID, VOUCHER_LINE_NUM ORDER BY VOUCHER_LINE_NUM) AS VOUCHER_LINE_NUM,
LINE_TYPE, MERCHANDISE_AMT, INVOICE_QTY, UNIT_PRICE, UNIT_OF_MEASURE, DESCR , BLANK1, BLANK2--A.PO_ID, A.LINE_NBR,
, BLANK3, BLANK4,
BLANK5, BLANK6,BLANK7,BLANK777,BLANK8,BLANK9,BLANK10,BLANK11,BLANK12,
SEGMENTS, BLANK13, DATE1, BLANK14,BLANK15,BLANK16,BLANK17, BLANK18,
BLANK19,BLANK199,BLANK1999,BLANK20,BLANK21,BLANK211,BLANK22,BLANK23,BLANK24,BLANK25,BLANK26,BLANK27,BLANK28,
BLANK29,BLANK30,BLANK31,
BLANK133,
BLANK134, BLANK32, BLANK33, BLANK34,
BLANK35, BLANK36,
BLANK37, BLANK38,BLANK39,BLANK40,BLANK41,BLANK411,BLANK42, BLANK43, BLANK44,BLANK45,BLANK46,BLANK47,BLANK48,BLANK49,BLANK50,BLANK51,BLANK52,BLANK53,BLANK54,BLANK55,BLANK56,BLANK57,BLANK58,BLANK59,BLANK60,BLANK61,BLANK62,BLANK63,BLANK64,BLANK65,BLANK66,BLANK67,BLANK68,BLANK69,BLANK70,BLANK71,BLANK72,BLANK73,BLANK74,BLANK75,BLANK76,BLANK77,BLANK78,BLANK79,BLANK80,
BLANK81,BLANK82,BLANK83,BLANK84,BLANK85,BLANK86,BLANK87,BLANK88,BLANK89,BLANK90,BLANK91,BLANK92,BLANK93,BLANK94,BLANK95,BLANK96,BLANK97,BLANK98,BLANK99,BLANK100,BLANK101,BLANK102,BLANK103,BLANK104,BLANK105,BLANK106,BLANK107,BLANK108,BLANK109,BLANK110,BLANK111,BLANK112,BLANK113,BLANK114,BLANK115,BLANK116,BLANK117,BLANK118,BLANK119,BLANK120,BLANK121,BLANK122,BLANK123,BLANK124,BLANK125,BLANK126,BLANK127,BLANK128,BLANK129,BLANK130,BLANK131,BLANK132 , value
FROM CTE
unpivot (value FOR col IN (MERCHANDISE_AMT, FREIGHT_AMT, SALETX_AMT)) u
WHERE value > 0.00
You cannot include MERCHANDISE_AMT here:
unpivot (value FOR col IN (MERCHANDISE_AMT, FREIGHT_AMT, SALETX_AMT)
AND in your final SELECT from the UNPIVOT results (4th column result set).
Including it in the IN list here means that you are unpivoting the value of this column into your row structure, so you can no longer select its value in your final SELECT.
So you need to pick. Do you want to unpivot the values in MERCHANDISE_AMT? If so, then leave it in the IN list of your UNPIVOT and remove it from final SELECT. If not, then remove it from your IN list and leave it in your final SELECT.
Seems like you would likely benefit from reading through the Microsoft examples on UNPIVOT.

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.

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()))))

SQL TOP 1 issue when no record is found

Hope you can help me with this SQL issue I am unable to solve:
I have a price list file with multiple entries per item number like this:
ItemNo
ValidFrom
ValidTo
Price
Now when I try to generate a list with prices valid today, I use the statement below to get a decent report. I only have a problem when no valid price was found, i.e. for TODAY there is no record. In this case the first TOP 1 subquery still returns a (random?) value and destroys my report.
I assume that TOP 1 will always return one value by definition, or is there a trick which can prevent this?
Really appreciate your help! (and please excuse the german terms in the query...)
SELECT
MITBAL.MBITNO as 'Artikel', MITMAS.MMITDS as 'Bezeichnung',
MITBAL.MBBUYE as 'Disponent', MITMAS.MMNEWE as 'Gewicht',
MITBAL.MBSUNO as 'Lieferant', MMITTY as 'Typ',
m9ucos as 'Std.-Kosten', idsunm as 'Lieferantenname',
iicucd as 'WSL', MBEOQT as 'EOQ',
(select count(*)
from RCE12_Staging.dbo.mpagrl
left outer join RCE12_Staging.dbo.mpagrh on aicono = ahcono
and aiagnb = ahagnb and aisuno = ahsuno
where aicono = 2
and aiobv1 = mbitno and aisagl = 20
and aisuno between '400000' and '599999' and aigrpi = 40
and aiuvdt >= CONVERT(char(8), GETDATE(), 112) and ahpast = '40') as 'Anz.Lief',
(select TOP 1 ajpupr
from RCE12_Staging.dbo.mpagrp
left outer join RCE12_Staging.dbo.mpagrh on ajcono = ahcono
and ajagnb = ahagnb and ajsuno = ahsuno
left outer join RCE12_Staging.dbo.mpagrl on ajcono = aicono
and ajagnb = aiagnb and ajsuno = aisuno
where ajcono = 2
and ajobv1 = mbitno and ajsuno = mbsuno
and ajmapr = 1 and ajgrpi = 40
and ajfvdt < CONVERT(char(8), GETDATE(), 112) and ahpast = '40'
and ahfvdt < CONVERT(char(8), GETDATE(), 112)
and ahuvdt >= CONVERT(char(8), GETDATE(), 112)
and aisagl = 20 and aigrpi = 40
and aifvdt < CONVERT(char(8), GETDATE(), 112)
and aiuvdt >= CONVERT(char(8), GETDATE(), 112)
order by ajfvdt desc) as 'EK-Preis',
(select TOP 1 ajfrqt
from RCE12_Staging.dbo.mpagrp
left outer join RCE12_Staging.dbo.mpagrh on ajcono = ahcono
and ajagnb = ahagnb and ajsuno = ahsuno
left outer join RCE12_Staging.dbo.mpagrl on ajcono = aicono
and ajagnb = aiagnb and ajsuno = aisuno
where ajcono = 2 and ajobv1 = mbitno
and ajsuno = mbsuno and ajmapr = 1 and ajgrpi = 40
and ajfvdt < CONVERT(char(8), GETDATE(), 112) and ahpast = '40'
and ahfvdt < CONVERT(char(8), GETDATE(), 112)
and ahuvdt >= CONVERT(char(8), GETDATE(), 112) and aisagl = 20
and aigrpi = 40
and aifvdt < CONVERT(char(8), GETDATE(), 112)
and aiuvdt >= CONVERT(char(8), GETDATE(), 112)
order by ajfvdt desc) as 'EK-Menge'
FROM
RCE12_Staging.dbo.MITBAL MITBAL
left outer join
RCE12_Staging.dbo.MITFAC MITFAC ON mbcono = m9cono and mbitno = m9itno and m9faci = 'DFP'
left outer join
RCE12_Staging.dbo.MITMAS MITMAS ON mbcono = mmcono and mbitno = mmitno
left outer join
RCE12_Staging.dbo.CIDMAS CIDMAS ON mbcono = idcono and mbsuno = idsuno
left outer join
RCE12_Staging.dbo.CIDVEN CIDVEN ON mbcono = iicono and mbsuno = iisuno
WHERE
MITBAL.MBCONO = 2
AND MITBAL.MBWHLO = '200' AND MBSTAT = '20' AND MBPUIT = '2'
and MBITNO like '479200222%'
ORDER BY MBITNO
The 'top 1' will return the first row from the dataset if the dataset you have requested is empty then top 1 will return an empty dataset with no rows and no 'Random data'.
You should probably check the number of rows returned if you need the data for later in the query or initialise a variable and use that.