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