Showing a row that doesn't exist - sql

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

Related

Show unique values only when using CTE - SQL Server

I have the following query:
with GTS_cte AS
(SELECT distinct [BusinessTermID], GTS_T =
STUFF ((SELECT ', ' + dbo.TblField.GTS_table
FROM dbo.TblField
WHERE [BusinessTermID] = Y.[BusinessTermID] AND dbo.TblField.GTS_table <> '' FOR XML PATH('')), 1, 2, '')
FROM dbo.Tblfield AS Y
GROUP BY [BusinessTermID])
,
syn_cte as (
SELECT [BusinessTermID], syns = STUFF
((SELECT ', ' + dbo.TblBusinessSynonym.Synonym
FROM dbo.TblBusinessSynonym
WHERE [BusinessTermID] = x.[BusinessTermID] AND dbo.TblBusinessSynonym.Synonym <> '' FOR XML PATH('')), 1, 2, '')
FROM dbo.TblBusinessSynonym AS x
GROUP BY [BusinessTermID])
select syn_cte.BusinessTermID, syn_cte.syns, GTS_cte.GTS_T
from syn_cte join
GTS_cte on GTS_cte.BusinessTermID = syn_cte.BusinessTermID
It is concatenating the fields correctly and linking them but it is now creating duplicates. My result set looks like this:
Is there a way to show only Unique values in GTS_T?
Thank you
Use DISTINCT inside your Sub-Query.
Try this:
;with GTS_cte AS
(SELECT [BusinessTermID], GTS_T =
STUFF ((SELECT DISTINCT ', ' + dbo.TblField.GTS_table
FROM dbo.TblField
WHERE [BusinessTermID] = Y.[BusinessTermID] AND dbo.TblField.GTS_table <> '' FOR XML PATH('')), 1, 2, '')
FROM dbo.Tblfield AS Y
GROUP BY [BusinessTermID])
,
syn_cte as (
SELECT [BusinessTermID], syns = STUFF
((SELECT DISTINCT ', ' + dbo.TblBusinessSynonym.Synonym
FROM dbo.TblBusinessSynonym
WHERE [BusinessTermID] = x.[BusinessTermID] AND dbo.TblBusinessSynonym.Synonym <> '' FOR XML PATH('')), 1, 2, '')
FROM dbo.TblBusinessSynonym AS x
GROUP BY [BusinessTermID])
select syn_cte.BusinessTermID, syn_cte.syns, GTS_cte.GTS_T
from syn_cte join
GTS_cte on GTS_cte.BusinessTermID = syn_cte.BusinessTermID

Get results only if it exists in a union tsql

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)

Execute the SQL query with if statement in Where clause

Need to execute the SQL query with IF statement in Where clause.
SELECT
CASE
WHEN Isnull(CustGuarFlag ,'') = '' THEN DocName
ELSE DocName + ' - '+
CASE
WHEN CustGuarFlag= 'C' THEN 'Customer'
ELSE 'Guarantor'
END
END DocName,
ISNULL(A.DOCSTAGE, '') DOCSTAGE,
ISNULL(A.DOCREFNO,'') DOCREFNO,
ISNULL(CONVERT(VARCHAR, A.DOCREFDT, 103), '') DOCREFDT,
ISNULL(CONVERT(VARCHAR, A.RECDDT, 103), '') RECDDT ,
ISNULL(A.DOCVALUE, 0) DOCVALUE ,
ISNULL(CONVERT(VARCHAR, A.DOCVLDUPTO, 103), '') DOCVLDUPTO,
a.pk_id AS AppDocpk,
b.pk_id AS Docpk,
CASE
WHEN Isnull(a.DocVerifiedStatus, '') = 'null'
THEN ''
ELSE Isnull(a.DocVerifiedStatus,'')
END AS DocVerifiedStatus,
ISNULL(RejRemarks, '') AS RejRemarks,
ISNULL(KYCDocHdr_Fk, 0) AS KYCPk,
ISNULL(DocShrtDescr, '') AS DocShrtDescr
FROM
loln_apprvldoc A WITH(NOLOCK)
JOIN
LGEN_DOCUMENTS B WITH(NOLOCK) ON A.Doc_FK = B.PK_ID
LEFT OUTER JOIN
Lgen_KYCApprvlDoc c ON a.KYCDocHdr_Fk = c.PK_Id
WHERE
A.PRPSLNO = 'KATHU1602080002'
AND ISNULL(A.DocStat, '') = 'R'
AND ISNULL(A.DocVerifiedStatus, '') IN ('Rejection', '', 'null')
AND CASE
WHEN Isnull(c.DocVerifiedStatus, '') = 'A'
THEN c.Pk_id IS NOT NULL
ELSE c.Pk_id IS NULL
END
CASE doesn't belong in a WHERE clause. Replace that CASE clause with
(
(Isnull(c.DocVerifiedStatus,'')='A' AND c.Pk_id IS NOT NULL)
OR
(Isnull(c.DocVerifiedStatus,'')<>'A' AND c.Pk_id IS NULL)
)

Return newest row when several columns are the same

I have a very complex Union query that returns up to two rows. If the second through the 15th columns are identical in both records, I want to return the results of the second record. Otherwise, return the results of the first record which is the newest record. The goal is to return the newest name and address with a pending flag only if the data is not the same.
SELECT TOP 1
1 AS updatePending,
a.entity_number,
a.name_title,
a.name_first,
a.name_middle,
a.name_last,
a.name_suffix,
LTRIM(RTRIM(REPLACE(
LTRIM(RTRIM(ISNULL(a.name_first, ''))) +
CASE WHEN LEN(LTRIM(RTRIM(ISNULL(a.name_first, '')))) = 1 THEN '. ' ELSE ' ' END +
LTRIM(RTRIM(ISNULL(a.name_middle, ''))) +
CASE WHEN LEN(LTRIM(RTRIM(ISNULL(a.name_middle, '')))) = 1 THEN '. ' ELSE ' ' END +
LTRIM(RTRIM(ISNULL(a.name_last, ''))) + ' ' +
LTRIM(RTRIM(ISNULL(a.name_suffix, '')))
,' ',' '))) AS name_full,
NULLIF(LTRIM(RTRIM(
LTRIM(RTRIM(ISNULL(a.company, ''))) +
LTRIM(RTRIM(ISNULL(a.firm_name, ''))))),'') AS company,
a.address1,
a.mailing_address,
a.city,
a.state,
a.zip_code AS zipcode,
a.internet_address AS email_address,
a.time_stamp
FROM statebar.dbo.STAGING_Address_Change_Request a
INNER JOIN Member m ON m.entity_number = a.entity_number
WHERE a.entity_number = (
SELECT m.entity_number
FROM Member m
INNER JOIN Named_Entity ne ON (ne.entity_number = m.entity_number)
WHERE ne.name_last = 'Park'
AND m.birth_year = '1958'
AND m.barno = '12345'
)
AND a.time_stamp > m.time_stamp
UNION ALL
SELECT TOP 1
0 AS updatePending,
ne.entity_number,
ne.name_title,
ne.name_first,
ne.name_middle,
ne.name_last,
ISNULL(ne.name_suffix, ''),
LTRIM(RTRIM(REPLACE(
LTRIM(RTRIM(ISNULL(ne.name_first, ''))) +
CASE WHEN LEN(LTRIM(RTRIM(ISNULL(ne.name_first, '')))) = 1 THEN '. ' ELSE ' ' END +
LTRIM(RTRIM(ISNULL(ne.name_middle, ''))) +
CASE WHEN LEN(LTRIM(RTRIM(ISNULL(ne.name_middle, '')))) = 1 THEN '. ' ELSE ' ' END +
LTRIM(RTRIM(ISNULL(ne.name_last, ''))) + ' ' +
LTRIM(RTRIM(ISNULL(ne.name_suffix, '')))
,' ',' '))) AS name_full,
NULLIF(LTRIM(RTRIM(
LTRIM(RTRIM(ISNULL(ne.company, ''))) +
LTRIM(RTRIM(ISNULL(ne.firm_name, ''))))),'') AS company,
ISNULL(ne.address1, ''),
ne.mailing_address,
ne.city,
ne.state,
ne.zip_code,
ne.internet_address AS email_address,
m.time_stamp
FROM Member m
INNER JOIN Named_Entity ne ON (ne.entity_number = m.entity_number)
LEFT JOIN statebar.dbo.STAGING_Address_Change_Request a ON a.entity_number = m.entity_number
WHERE ne.entity_number = (
SELECT m.entity_number
FROM Member m
INNER JOIN Named_Entity ne ON (ne.entity_number = m.entity_number)
WHERE ne.name_last = 'Park'
AND m.birth_year = '1958'
AND m.barno = '12345'
)
AND m.time_stamp > a.time_stamp
ORDER BY updatePending DESC, a.time_stamp DESC

Looking to optimize multiple JOINs into one dynamic JOIN - Possible?

So I currently have a query that pulls in buyer and seller names into a single column value. I am utilizing a CASE statement for if one of the buyer or seller values is NULL, and also since the user can delete the buyer or seller and it retains its original Sequence value (1, 2, 3, etc..) So for instance, say I have the following entries in the BuyerSeller table:
OrdersID | Sequence | BuyerSellerType | FormalName
------------------------------------------------------
1 | 1 | 0 | Billy Bob
1 | 2 | 0 | Sally Sue
1 | 1 | 1 | Joe Dirt
1 | 3 | 1 | Dwayne Johnson
My SELECT statement below will return the following:
BuyerFormalName | SellerFormalName
-----------------------------------------------
Billy Bob, Sally Sue | Joe Dirt, Dwayne Johnson
Here's the statement. Now, I am just trying to see if there is any way to dynamically or more easily produce the same results without the need for so many JOINs? I am getting the results I want, but I am looking to fine tune my skills and knowledge, especially since I might have to potentially add >3 more JOINs. Any insight would be very much appreciated!
SELECT
CASE
WHEN ISNULL(B.FormalName,'') <> '' AND ISNULL(B2.FormalName,'') <> '' AND ISNULL(B3.FormalName,'') <> ''
THEN B.FormalName + ', ' + B2.FormalName + ', ' + B3.FormalName
WHEN ISNULL(B.FormalName,'') <> '' AND ISNULL(B2.FormalName,'') = '' AND ISNULL(B3.FormalName,'') <> ''
THEN B.FormalName + ', ' + B3.FormalName
WHEN ISNULL(B.FormalName,'') <> '' AND ISNULL(B2.FormalName,'') <> '' AND ISNULL(B3.FormalName,'') = ''
THEN B.FormalName + ', ' + B2.FormalName
WHEN ISNULL(B.FormalName,'') = '' AND ISNULL(B2.FormalName,'') <> '' AND ISNULL(B3.FormalName,'') <> ''
THEN B2.FormalName + ', ' + B3.FormalName
WHEN ISNULL(B.FormalName,'') = '' AND ISNULL(B2.FormalName,'') <> '' AND ISNULL(B3.FormalName,'') = ''
THEN B2.FormalName
WHEN ISNULL(B.FormalName,'') = '' AND ISNULL(B2.FormalName,'') = '' AND ISNULL(B3.FormalName,'') <> ''
THEN B3.FormalName
ELSE B.FormalName
END AS 'BuyerFormalName'
,CASE
WHEN ISNULL(S.FormalName,'') <> '' AND ISNULL(S2.FormalName,'') <> '' AND ISNULL(S3.FormalName,'') <> ''
THEN S.FormalName + ', ' + S2.FormalName + ', ' + S3.FormalName
WHEN ISNULL(S.FormalName,'') <> '' AND ISNULL(S2.FormalName,'') = '' AND ISNULL(S3.FormalName,'') <> ''
THEN S.FormalName + ', ' + S3.FormalName
WHEN ISNULL(S.FormalName,'') <> '' AND ISNULL(S2.FormalName,'') <> '' AND ISNULL(S3.FormalName,'') = ''
THEN S.FormalName + ', ' + S2.FormalName
WHEN ISNULL(S.FormalName,'') = '' AND ISNULL(S2.FormalName,'') <> '' AND ISNULL(S3.FormalName,'') <> ''
THEN S2.FormalName + ', ' + S3.FormalName
WHEN ISNULL(S.FormalName,'') = '' AND ISNULL(S2.FormalName,'') <> '' AND ISNULL(S3.FormalName,'') = ''
THEN S2.FormalName
WHEN ISNULL(S.FormalName,'') = '' AND ISNULL(S2.FormalName,'') = '' AND ISNULL(S3.FormalName,'') <> ''
THEN S3.FormalName
ELSE S.FormalName
END AS 'SellerFormalName'
FROM
Checks C
LEFT JOIN BuyerSeller B
ON C.OrdersID = B.OrdersID
AND B.Sequence = 1
AND B.BuyerSellerType = 0
LEFT JOIN BuyerSeller B2
ON C.OrdersID = B2.OrdersID
AND B2.Sequence = 2
AND B2.BuyerSellerType = 0
LEFT JOIN BuyerSeller B3
ON C.OrdersID = B3.OrdersID
AND B3.Sequence = 3
AND B3.BuyerSellerType = 0
LEFT JOIN BuyerSeller S
ON C.OrdersID = S.OrdersID
AND S.Sequence = 1
AND S.BuyerSellerType = 1
LEFT JOIN BuyerSeller S2
ON C.OrdersID = S2.OrdersID
AND S2.Sequence = 2
AND S2.BuyerSellerType = 1
LEFT JOIN BuyerSeller S3
ON C.OrdersID = S3.OrdersID
AND S3.Sequence = 3
AND S3.BuyerSellerType = 1
Are you looking for something like this?
WITH BuyerSeller
AS
(
SELECT *
FROM
(
VALUES (1,1,0,'Billy Bob'),
(1,2,0,'Sally Sue'),
(1,1,1,'Joe Dirt'),
(1,3,1,'Dwayne Johnson')
) A(OrdersID,[Sequence],BuyerSellerType,FormalName)
)
SELECT DISTINCT OrdersID,
STUFF(Bname,1,2,'') AS BuyerFormalName,
STUFF(Sname,1,2,'') AS SellerFormalName
FROM BuyerSeller A
CROSS APPLY (
SELECT ', ' + FormalName
FROM BuyerSeller B
WHERE A.OrdersID = B.OrdersID
AND BuyerSellerType = 0
ORDER BY [Sequence]
FOR XML PATH('')
) CA(Bname)
CROSS APPLY (
SELECT ', ' + FormalName
FROM BuyerSeller B
WHERE A.OrdersID = B.OrdersID
AND BuyerSellerType = 1
ORDER BY [Sequence]
FOR XML PATH('')
) CA2(Sname)
Results:
OrdersID BuyerFormalName SellerFormalName
----------- --------------------- -----------------------
1 Billy Bob, Sally Sue Joe Dirt, Dwayne Johnson
I still prefer old-style MAX/CASE in such a case if the number of rows/values is known (and small):
SELECT
c.OrdersID,
BuyerFormalName,
SellerFormalName
FROM Checks C
LEFT JOIN
(
SELECT
OrdersID,
STUFF(MAX(CASE WHEN Sequence = 1 AND BuyerSellerType = 0 THEN ', ' + FormalName ELSE '' end) +
MAX(CASE WHEN Sequence = 2 AND BuyerSellerType = 0 THEN ', ' + FormalName ELSE '' end) +
MAX(CASE WHEN Sequence = 3 AND BuyerSellerType = 0 THEN ', ' + FormalName ELSE '' end), 1,2,'') AS BuyerFormalName,
STUFF(MAX(CASE WHEN Sequence = 1 AND BuyerSellerType = 1 THEN ', ' + FormalName ELSE '' end) +
MAX(CASE WHEN Sequence = 2 AND BuyerSellerType = 1 THEN ', ' + FormalName ELSE '' end) +
MAX(CASE WHEN Sequence = 3 AND BuyerSellerType = 1 THEN ', ' + FormalName ELSE '' end), 1,2,'') AS SellerFormalName
FROM BuyerSeller
GROUP BY OrdersID
) AS b
ON C.OrdersID = B.OrdersID
;