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

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
;

Related

conditional clause in Claudera

I am trying to get an if, then clause working in cloudera - along the lines:
if (appointment_purpose = '') and
appointment_purpose2 = '') and
appointment_type2 = '') and
appointment_type3 = '') and
appointment_type4 = '') and
appointment_type5 = '') and
discuss_other ' ') then
discuss_other = 0
else discuss_other = 1,
How do I get this to work?
If all appointment types and appointment purposes were empty, then discuss_other should also be empty, that is 0 - otherwise discuss_other should be 1
Try this:
SELECT (CASE WHEN appointment_purpose = ''
AND appointment_purpose2 = ''
AND appointment_type2 = ''
AND appointment_type3 = ''
AND appointment_type4 = ''
AND appointment_type5 = ''
AND discuss_other ' '
THEN 0
ELSE 1
) as discuss_other
FROM tableName
In SQL, "empty" typically means NULL. So, I wonder if you really intend one of these constructs:
select (case when appointment_purpose is null and
appointment_purpose2 is null and
appointment_type2 is null and
appointment_type3 is null and
appointment_type4 is null and
appointment_type5 is null and
discuss_other is null
then 0 else 1
end) as discuss_other
Because one of the values has a space, I wonder if you want to handle both spaces and null values:
select (case when (appointment_purpose is null or replace(appointment_purpose, ' ', '') = '') and
(appointment_purpose2 is null or replace(appointment_purpose2, ' ', '') = '') and
(appointment_purpose3 is null or replace(appointment_purpose3, ' ', '') = '') and
(appointment_purpose4 is null or replace(appointment_purpose4, ' ', '') = '') and
(appointment_purpose5 is null or replace(appointment_purpose5, ' ', '') = '') and
(discuss_other is null or replace(discuss_other, ' ', '') = '')
then 0 else 1
end) as discuss_other
Finally, multiple columns in the same table that are acting like an array is usually a bad sign. Normally, this suggests that you want a junction table.

SQL add conversion of date to existing query

I'm would like to convert the date using this function. I'm using SQL server 2014
CONVERT(varchar, sc.StartDate,103) + '" + " " + "' + '" + " - " + "' + CONVERT(varchar, sc.EndDate,103) SIPDate
so it will display in dd/mm/yyyy - dd/mm/yyyy. How do i add it into the query? Thanks.
The query is:
SELECT CONCAT(sc.StartDate, sc.ENDDate) SIPDate,
COUNT (sj.LOComment) WeekReviewed,
COUNT(sjd.WeekNo) TotalWeek,
SUM(sjj.TotalDaysRecord) TotalDaysRecord,
COUNT(CASE sjd.JournalStatusCode WHEN 'D' THEN 1 ELSE NULL END) PENDingComplete
FROM StudentJournalDate sjd
LEFT JOIN StudentJournal sj
ON sjd.WeekNo = sj.WeekNo
LEFT OUTER JOIN
(
SELECT sj.WeekNo,
CASE WHEN RTRIM(sj.Day1Journal) = '' OR sj.Day1Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day2Journal) = '' OR sj.Day2Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day3Journal) = '' OR sj.Day3Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day4Journal) = '' OR sj.Day4Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day5Journal) = '' OR sj.Day5Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day6Journal) = '' OR sj.Day6Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day7Journal) = '' OR sj.Day7Journal IS NULL THEN 0 ELSE 1 END AS TotalDaysRecord
FROM StudentJournal sj
) AS sjj
ON sjj.WeekNo = sj.WeekNo
LEFT OUTER JOIN StudentSIP sc
ON sc.AdminNo = sjd.AdminNo
GROUP BY CONCAT(sc.StartDate, sc.ENDDate)
You can just SELECT and GROUP BY this formatted date expression, i.e.:
SELECT CONVERT(varchar, sc.StartDate, 103) + " - " + CONVERT(varchar, sc.EndDate, 103) AS SIPDate,
COUNT (sj.LOComment) WeekReviewed,
COUNT(sjd.WeekNo) TotalWeek,
SUM(sjj.TotalDaysRecord) TotalDaysRecord,
COUNT(CASE sjd.JournalStatusCode WHEN 'D' THEN 1 ELSE NULL END) PENDingComplete
FROM StudentJournalDate sjd
LEFT JOIN StudentJournal sj
ON sjd.WeekNo = sj.WeekNo
LEFT OUTER JOIN
(
SELECT sj.WeekNo,
CASE WHEN RTRIM(sj.Day1Journal) = '' OR sj.Day1Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day2Journal) = '' OR sj.Day2Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day3Journal) = '' OR sj.Day3Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day4Journal) = '' OR sj.Day4Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day5Journal) = '' OR sj.Day5Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day6Journal) = '' OR sj.Day6Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day7Journal) = '' OR sj.Day7Journal IS NULL THEN 0 ELSE 1 END AS TotalDaysRecord
FROM StudentJournal sj
) AS sjj
ON sjj.WeekNo = sj.WeekNo
LEFT OUTER JOIN StudentSIP sc
ON sc.AdminNo = sjd.AdminNo
GROUP BY CONVERT(varchar, sc.StartDate, 103) + " - " + CONVERT(varchar, sc.EndDate, 103)
Try this. since your SQL SERVER is 2014 you can use format to format the date
SELECT CONCAT(FORMAT(sc.StartDate,'dd/MM/yyy'),+ ' - ' +FORMAT(sc.ENDDate,'dd/MM/yyy')) SIPDate,
COUNT (sj.LOComment) WeekReviewed,
COUNT(sjd.WeekNo) TotalWeek,
SUM(sjj.TotalDaysRecord) TotalDaysRecord,
COUNT(CASE sjd.JournalStatusCode WHEN 'D' THEN 1 ELSE NULL END) PENDingComplete
FROM StudentJournalDate sjd
LEFT JOIN StudentJournal sj
ON sjd.WeekNo = sj.WeekNo
LEFT OUTER JOIN
(
SELECT sj.WeekNo,
CASE WHEN RTRIM(sj.Day1Journal) = '' OR sj.Day1Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day2Journal) = '' OR sj.Day2Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day3Journal) = '' OR sj.Day3Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day4Journal) = '' OR sj.Day4Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day5Journal) = '' OR sj.Day5Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day6Journal) = '' OR sj.Day6Journal IS NULL THEN 0 ELSE 1 END +
CASE WHEN RTRIM(sj.Day7Journal) = '' OR sj.Day7Journal IS NULL THEN 0 ELSE 1 END AS TotalDaysRecord
FROM StudentJournal sj
) AS sjj
ON sjj.WeekNo = sj.WeekNo
LEFT OUTER JOIN StudentSIP sc
ON sc.AdminNo = sjd.AdminNo
GROUP BY CONCAT(FORMAT(sc.StartDate,'dd/MM/yyy'),+ ' - ' +FORMAT(sc.ENDDate,'dd/MM/yyy'))

Adding a '|' character to a case statement in a stored procedure

I have the following case statement in a stored procedure:
Position = case coalesce(teamMember.JobTitle, '') when '' then '' else '<b>' + coalesce(teamMember.JobTitle, '') + '</b>' end
+ isnull(teamMember.OrganizationNameLevel1, '')
+ case when isnull(teamMember.OrganizationNameLevel2, '') <> isnull(teamMember.OrganizationNameLevel1, '') THEN ' | ' + isnull(teamMember.OrganizationNameLevel2, '') ELSE '' END
+ case when isnull(teamMember.OrganizationNameLevel3, '') <> isnull(teamMember.OrganizationNameLevel2, '') THEN ' | ' + isnull(teamMember.OrganizationNameLevel3, '') ELSE '' END
+ case when isnull(teamMember.OrganizationNameLevel4, '') <> isnull(teamMember.OrganizationNameLevel3, '') THEN ' | ' + isnull(teamMember.OrganizationNameLevel4, '') ELSE '' END
+ case when isnull(teamMember.OrganizationNameLevel5, '') <> isnull(teamMember.OrganizationNameLevel4, '') THEN ' | ' + isnull(teamMember.OrganizationNameLevel5, '') ELSE '' END
+ case when isnull(teamMember.OrganizationNameLevel6, '') <> isnull(teamMember.OrganizationNameLevel5, '') THEN ' | ' + isnull(teamMember.OrganizationNameLevel6, '') ELSE '' END,
It produces the following result:
<b>APPS SYSTEMS ENGINEER</b>TECH & OPS | ENT INFO TECH | DEP & OPS TECH | HR SYS & ITECH | COMP & BEN APPS
What I need is for it to show is this:
**<b>APPS SYSTEMS ENGINEER</b> |** TECH & OPS | ENT INFO TECH | DEP & OPS TECH | HR SYS & ITECH | COMP & BEN APPS
Shouldn't it be as simple as:
Position = case coalesce(teamMember.JobTitle, '') when '' then '' else '<b>' + coalesce(teamMember.JobTitle, '') + '</b>' end
+ isnull(' | ' + teamMember.OrganizationNameLevel1, '') --<-- add a Pipe here inside the ISNULL function
+ case when isnull(teamMember.OrganizationNameLevel2, '') <> isnull(teamMember.OrganizationNameLevel1, '') THEN ' | ' + isnull(teamMember.OrganizationNameLevel2, '') ELSE '' END
+ .........

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

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