Full Outer Join based off multiple fields - sql

Here is the situation that I'm facing:
I have two tables A and B. If records are in table A and not in table B they need to be added to table B. If records are in table B and not in table A, then they need to be removed out of table B. The trick here is that it is the mixture of two keys that makes the unique combination
Table A
Operation_Key Part_Key
1 1
1 2
2 1
2 3
Table B
Operation_Key Part_Key Record_Key
1 1 1
2 1 2
2 3 3
2 4 4
I am trying to get the right type of query so that the results returned look like
Results
Operation_Key Part_Key Record_Key Action
1 2 NULL Add
2 4 4 Delete
The query I have so far looks like similar to this:
CREATE TABLE #Action_Table
(
Action VARCHAR(6),
Action_Bit INT,
Operation_Key INT,
Record_Key INT,
Part_Key INT
)
INSERT INTO #Action_Table
SELECT
CASE
WHEN WS.Operation_Key IS NULL THEN 'Delete'
WHEN WS.Operation_Key IS NOT NULL THEN 'Add'
END Action,
CASE
WHEN WS.Operation_Key IS NULL THEN '0'
WHEN WS.Operation_Key IS NOT NULL THEN '1'
END Action_Bit,
CASE
WHEN WS.Operation_Key IS NULL THEN WC.Operation_Key
WHEN WS.Operation_Key IS NOT NULL THEN WS.Operation_Key
END Operation_Key,
CASE
WHEN WS.Operation_Key IS NULL THEN WC.Record_Key
WHEN WS.Operation_Key IS NOT NULL THEN NULL
END Workcenter_Component_Key,
CASE
WHEN WS.Operation_Key IS NULL THEN WC.Part_Key
WHEN WS.Operation_Key IS NOT NULL THEN WS.Part_Key
END Part_Key
FROM #WS_Part_Table WS
FULL OUTER JOIN #WC_Part_Table WC
ON WC.Part_Key = WS.Part_Key
AND WC.Operation_Key = WS.Operation_Key
WHERE (WS.Part_Key IS NULL or WC.Part_Key IS NULL) AND (WS.Operation_Key IS NULL or WC.Operation_Key IS NULL)
Both the #WS_Part_Table and the #WC_Part_Table are temp tables that I'm constructing using queries, but my dilemma is that I have to PRE-QUERY the #WC_Part_Table query on the operation key that I'm interested in, otherwise I get way too many results.
This is the query that I'm using to create the #WC_Part_Table
CREATE TABLE #WC_Part_Table
(
Operation_Key INT,
Record_Key INT,
Part_Key INT
)
-- Workcenter Component Table
INSERT INTO #WC_Part_Table
SELECT
O.Operation_Key,
WC.Record_Key,
WC.Part_Key
FROM Workcenter_Component WC
JOIN Operation O
ON O.Default_Workcenter_Key = WC.Workcenter_Key
/* There is some reason why this next line is needed */
WHERE O.Operation_Key = 23149

Tyr this to get the results that you have posted:
SELECT COALESCE(a.Operation_Key, b.Operation_Key) Operation_Key,
COALESCE(a.Part_Key, b.Part_Key) Part_Key,
Record_Key,
CASE
WHEN Record_Key IS NULL THEN 'Add'
ELSE 'Delete'
END Action
FROM TableA a FULL OUTER JOIN TableB b
ON a.Operation_Key = b.Operation_Key
AND a.Part_Key = b.Part_Key
WHERE (a.Operation_Key IS NULL) OR (b.Operation_Key IS NULL)
Test Script:
CREATE TABLE #TableA
(
Operation_Key INT,
Part_Key INT
)
INSERT INTO #TableA
SELECT 1,1
UNION
SELECT 1,2
UNION
SELECT 2,1
UNION
SELECT 2,3
CREATE TABLE #TableB
(
Operation_Key INT,
Part_Key INT,
Record_Key INT
)
INSERT INTO #TableB
SELECT 1,1,1
UNION
SELECT 2,1,2
UNION
SELECT 2,3,3
UNION
SELECT 2,4,4
SELECT COALESCE(a.Operation_Key, b.Operation_Key) Operation_Key,
COALESCE(a.Part_Key, b.Part_Key) Part_Key,
Record_Key,
CASE
WHEN Record_Key IS NULL THEN 'Add'
ELSE 'Delete'
END Action
FROM #TableA a FULL OUTER JOIN #TableB b
ON a.Operation_Key = b.Operation_Key
AND a.Part_Key = b.Part_Key
WHERE (a.Operation_Key IS NULL) OR (b.Operation_Key IS NULL)
Output:
Operation_Key Part_Key Record_Key Action
1 2 NULL Add
2 4 4 Delete

Add to B:
insert into B (Operation_Key, Part_Key, Record_Key)
values
select Operation_Key, Part_Key, null as Record_Key from A
left join b on a.Operation_Key = b.Operation_Key and
a.Part_Key = b.Part_Key
where b.Part_Key is null
Delete from B:
Delete from B
select * from B left join A on b.Operation_Key = a.Operation_Key and
b.Part_Key = a.Part_Key
where a.Operation_Key is null

You can get exactly the results table you want (looking at your example set up) by making clever use of the SQL "COALESCE" operator. If you use a query like this:
SELECT
COALESCE(A.Operation_Key, B.Operation_Key) as Operation_Key,
COALESCE(A.part_key, B.part_key) as Part_Key,
B.Record_Key,
CASE WHEN A.Operation_Key IS NULL THEN
'Delete'
ELSE
'Add'
END AS [Action] FROM A
FULL OUTER JOIN B
ON A.Operation_Key = B.Operation_Key
AND A.Part_Key= B.Part_Key
WHERE A.Operation_Key IS NULL
OR B.Operation_Key IS NULL
...you'll get a result table exactly like your example.

Related

Insert values to a table from another table based on condition

So I have a SQL table in which I am entering values by joining other columns and entering the column values from that table.
CREATE TABLE #temp_t (id INT, cname NVARCHAR(100), val INT, aid INT)
INSERT INTO #temp_t
SELECT DISTINCT
ISNULL(IDXC.id, 0) id, sg.name + '-webApp' cName, 0 val, ag.ID aid
FROM spgroup sg
JOIN APPA APP ON sg.id > 1 AND sg.val & 4 = 0 AND APP.dagi = sg.id
JOIN AIDBI XDI ON APP.bs = XDI.bsid
LEFT JOIN #IDXC ON IDXC.agpv = sg.id
WHERE IDXC.id IS NULL
Now while inserting values to the table I need to check if sg.name exists in sysName table if yes then -webApp needs to be replaced by -andApp otherwise it remains -webApp
How can I do the same?
You can use EXISTS in a CASE expression:
SELECT DISTINCT COALESCE(i.id, 0) as id,
(sg.name +
(CASE WHEN EXISTS (SELECT 1 FROM sysname sn WHERE sn.name = sg.name)
THEN '-andApp' ELSE '-webApp'
END)
) as cName,
0 as val, ag.ID as aid
FROM spgroup sg JOIN
APPA APP
ON sg.id > 1 AND (sg.val & 4) = 0 AND APP.dagi = sg.id JOIN
AIDBI XDI
ON APP.bs = XDI.bsid LEFT JOIN
#IDXC i
ON i.IDXCsgpv = sg.id
WHERE i.id IS NULL

Combine two table for one output sql query

I have two tables
Threads:
i_id thread_note seq_id
1 ABC 2
2 CDE 2
3 FGH 1
4 IJK 2
Notes:
i_id note_text entered_date
1 stack 09/08/2017
5 queue 07/07/2014
3 push 09/07/1996
I want the output as
i_id thread_note seq_id note_text entered_date
1 ABC 2 stack 09/08/2017
2 CDE 2 null null
3 FGH 1 push 09/07/1996
4 IJK 2 null null
5 null null queue 07/07/2014
How do I achieve this? The tables are not related to each other.
Note: This is different from most of the questions similar to this asked because there are some "i_id" values which are present in threads table but not in notes table and there are some "i_id" values present in notes table but not in threads table
Use a full outer join:
SELECT
COALESCE(t.i_id, n.i_id) AS i_id,
t.thread_note,
t.seq_id,
n.note_text,
n.entered_date
FROM Threads t
FULL OUTER JOIN Notes n
ON n.i_id = t.i_id
ORDER BY
i_id;
Note that having the need to do a full outer join often can indicate a problem with your relational model, because it means you don't know the key relationships between your tables.
Demo
Edit:
If you are using a database such as MySQL which does not support a full outer join, we can still simulate one:
SELECT *
FROM Threads t
LEFT JOIN Notes n
ON n.i_id = t.i_id
UNION ALL
SELECT *
FROM Threads t
RIGHT JOIN Notes n
ON n.i_id = t.i_id
WHERE t.i_id IS NULL;
First, you need to get all i_id from all tables in a subquery. Once you have the rows, join this to the two tables to get the columns you need,
SELECT a.i_id,
b.thread_note,
b.seq_id,
c.Note_text,
c.entered_date
FROM
(
SELECT i_id FROM Threads UNION
SELECT i_id FROM Notes
) a
LEFT JOIN Threads b
ON a.i_id = b.i_id
LEFT JOIN Notes c
ON a.i_id = c.i_id
ORDER BY a.i_id
Here's a Demo.
You could just use a FULL OUTER JOIN here. If I make some test data:
DECLARE #threads TABLE (i_id INT, thread_note NVARCHAR(3), seq_id INT);
INSERT INTO #threads SELECT 1, 'ABC', 2;
INSERT INTO #threads SELECT 2, 'CDE', 2;
INSERT INTO #threads SELECT 3, 'FGH', 1;
INSERT INTO #threads SELECT 4, 'IJK', 2;
DECLARE #notes TABLE (i_id INT, note_text NVARCHAR(10), entered_date DATE);
INSERT INTO #notes SELECT 1, 'stack', '20170809';
INSERT INTO #notes SELECT 5, 'queue', '20140707';
INSERT INTO #notes SELECT 3, 'push', '19960709';
Then my query is simply:
SELECT
ISNULL(t.i_id, n.i_id) AS i_id,
t.thread_note,
t.seq_id,
n.note_text,
n.entered_date
FROM
#threads t
FULL OUTER JOIN #notes n ON n.i_id = t.i_id
ORDER BY
ISNULL(t.i_id, n.i_id);
No need to make a list of unique I_ids.
Use the below query
select Isnull(n.i_id,t.i_id), [thread_note],seq_id,Notetest,Enddate
from [dbo].[note] n FULL OUTER JOIN [dbo].[thread] t on n.[i_id]=t.[i_id]
order by Isnull(n.i_id,t.i_id)

Select mismatched column values from Two Tables

I have two tables which has same column names.
For example:
NEEDTOSYNCREQUESTS table
Column Name Value
----------------------------
ID 1
LoadId L1
ShipmentId 123
OrderId NULL
PackageId P456
CustomerOTP 99999
ClientOTP 88888
LASTSYNCEDREQUEST table:
Column Name Value
-------------------------
ID 1
LoadId L1
ShipmentId NULL
OrderId 1234567
PackageId P456
CustomerOTP 44444
ClientOTP 686868
If you compare the above table's column valuesy You could see the following:
CustomerOTP & ClientOTP columns values are not identical.
ShipmentId Column in NEEDTOSYNCREQUESTS has value and ShipmentId Column in LASTSYNCEDREQUEST Table is NULL.
OrderId Column in LASTSYNCEDREQUEST Table has value and ShipmentId Column in NEEDTOSYNCREQUESTS Table is NULL.
So, I need to get the following output. How to achieve this?
OUTPUT
Column Name Value
---------------------------------
ID 1
LoadId NULL
ShipmentId 123
OrderId NULL
PackageId NULL
CustomerOTP 99999
ClientOTP 88888
The condition is, I need to compare the above two tables and needed only the updated column values NEEDTOSYNCREQUESTS Table when compared with another LASTSYNCEDREQUEST Table. Note: Both the columns have same values or NEEDTOSYNCREQUESTS Table Column does not have values then those columns should be null in the Output. PackageId in both the Table is Identical(same). So, I need PackageId to be NULL in the output.
Please help me to achieve this in a SQL query.
Thanks in advance!
As you can see, the same rules implemented in 3 WHENs in a CASE statement for all fields.
SELECT A.ID,
CASE WHEN A.LOADID = B.LOADID THEN NULL
WHEN A.LOADID IS NULL THEN NULL
WHEN (B.LOADID IS NULL AND A.LOADID IS NOT NULL) OR (A.LOADID IS NOT NULL AND B.LOADID IS NOT NULL) THEN A.LOADID END AS LOADID,
CASE WHEN A.SHIPMENTID = B.SHIPMENTID THEN NULL
WHEN A.SHIPMENTID IS NULL THEN NULL
WHEN (B.SHIPMENTID IS NULL AND A.SHIPMENTID IS NOT NULL) OR (A.SHIPMENTID IS NOT NULL AND B.SHIPMENTID IS NOT NULL) THEN A.SHIPMENTID END AS SHIPMENTID,
CASE WHEN A.ORDERID = B.ORDERID THEN NULL
WHEN A.ORDERID IS NULL THEN NULL
WHEN (B.ORDERID IS NULL AND A.ORDERID IS NOT NULL) OR (A.ORDERID IS NOT NULL AND B.ORDERID IS NOT NULL) THEN A.ORDERID END AS ORDERID,
CASE WHEN A.PACKAGEID = B.PACKAGEID THEN NULL
WHEN A.PACKAGEID IS NULL THEN NULL
WHEN (B.PACKAGEID IS NULL AND A.PACKAGEID IS NOT NULL) OR (A.PACKAGEID IS NOT NULL AND B.PACKAGEID IS NOT NULL) THEN A.PACKAGEID END AS PACKAGEID,
CASE WHEN A.CUSTOMEROTP = B.CUSTOMEROTP THEN NULL
WHEN A.CUSTOMEROTP IS NULL THEN NULL
WHEN (B.CUSTOMEROTP IS NULL AND A.CUSTOMEROTP IS NOT NULL) OR (A.CUSTOMEROTP IS NOT NULL AND B.CUSTOMEROTP IS NOT NULL) THEN A.CUSTOMEROTP END AS CUSTOMEROTP,
CASE WHEN A.CLIENTOTP = B.CLIENTOTP THEN NULL
WHEN A.CLIENTOTP IS NULL THEN NULL
WHEN (B.CLIENTOTP IS NULL AND A.CLIENTOTP IS NOT NULL) OR (A.CLIENTOTP IS NOT NULL AND B.CLIENTOTP IS NOT NULL) THEN A.CLIENTOTP END AS CLIENTOTP
FROM
NEEDTOSYNCREQUESTS A
INNER JOIN
LASTSYNCEDREQUEST B
ON A.ID = B.ID;
you can try a case based query like below
See live demo
select
id = N.id,
Loadid = case
when ISNULL(N.Loadid,'')=ISNULL(L.Loadid,'')
then NULL
else N.LoadId
end,
Shipmentid=case
when ISNULL(N.Shipmentid,'')=ISNULL(L.Shipmentid,'')
then NULL
else N.Shipmentid
end,
orderid=case
when ISNULL(N.orderid,'')=ISNULL(L.orderid,'')
then NULL
else N.orderid
end,
packageid=case
when ISNULL(N.packageid,'')=ISNULL(L.packageid,'')
then NULL
else N.packageid
end,
customerOTP=case
when ISNULL(N.customerOTP,'')=ISNULL(L.customerOTP,'')
then NULL
else N.customerOTP
end,
clientOTP=case
when ISNULL(N.clientOTP,'')=ISNULL(L.clientOTP,'')
then NULL
else N.clientOTP
end
from
NEEDTOSYNCREQUESTS N LEFT JOIN
LASTSYNCEDREQUEST L ON
N.id=L.id
Try this:
SELECT n.ID, n.LoadId, n.ShipmentId,
n.OrderId, NULL PackageId, n.CustomerOTP,
n.ClientOTP
FROM NEEDTOSYNCREQUESTS AS n
INNER JOIN LASTSYNCEDREQUEST AS l ON n.ID = l.ID AND n.LoadId = l.LoadId
WHERE n.CustomerOTP <> l.CustomerOTP AND
n.ClientOTP <> l.ClientOTP
AND n.ShipmentId IS NOT NULL
AND l.ShipmentId IS NULL
AND l.OrderId IS NOT NULL
AND l.ShipmentId IS NULL;
SQL Fiddle Demo
| ID | LoadId | ShipmentId | OrderId | PackageId | CustomerOTP | ClientOTP |
|----|--------|------------|---------|-----------|-------------|-----------|
| 1 | L1 | 123 | (null) | (null) | 99999 | 88888 |
Note that, I don't understand why the PackageId should be null, because according to your criteria, it shouldn't. Anyway, I select it as a fixed NULL value, so that you will always get a NULL value no matter what is the actual value.
I often have to solve some case like this when creating data extraction or integration.
So the answer for me will be close to this :
you can use the MERGE function and add some switch case if you want to custom it for some column
MERGE LASTSYNCEDREQUEST TGT
USING (
SELECT
ID,
LoadId,
ShipmentId,
OrderId,
PackageId,
CustomerOTP,
ClientOTP
FROM NEEDTOSYNCREQUESTS
) AS SRC
ON (
SRC.ID = TGT.ID)
WHEN MATCHED
THEN
UPDATE
SET
TGT.ID = SRC.ID
,TGT.LoadID = NULL
,TGT.ShipmentID = SRC.ShipmentID
,TGT.OrderID = NULL
,TGT.PackageID = NULL
,TGT.CustomerOTP = SRC.CustomerOTP
,TGT.ClientOTP = SRC.ClientOTP
WHEN NOT MATCHED
THEN
INSERT (
ID,
LoadId,
ShipmentId,
OrderId,
PackageId,
CustomerOTP,
ClientOTP
)
VALUES (
SRC.ID,
NULL,
SRC.ShipmentId,
NULL,
NULL,
SRC.CustomerOTP,
SRC.ClientOTP
);
SELECT * FROM LASTSYNCEDREQUEST
you can try the code that I write above.

Update table based on comparing data from different tables and priority

Say I have the below table which holds customer data:
DECLARE #customer TABLE (ref varchar(10), RepName varchar(10), City varchar(10))
INSERT INTO #customer
SELECT 'CustomerA', 'Tom', 'London' UNION ALL
SELECT 'CustomerC', 'John', 'London'
and I have 2 other identical tables SourceA and SourceB which holds customer data as well,
I have a script which compares data among these 3 tables and inserts the details into the below table:
DECLARE #diffs TABLE (ref varchar(10), existing_value varchar(100), nev_value varchar(100), source_table varchar(100), column_name varchar(100))
INSERT INTO #diffs
SELECT 'CustomerA', 'Tom', 'Tom A', 'SourceA', 'RepName' UNION ALL
SELECT 'CustomerA', 'Tom', 'Tom Ax', 'SourceB', 'RepName' UNION ALL
SELECT 'CustomerC', 'London', 'New York', 'SourceA', 'City'
This table highlights that the rep name in our Customer table is different than sourceA and sourceB. Current value is Tom, but sourceA has the value as Tom A and sourceB has it as Tom Ax, and it also highlights the difference in city but the city is only different in sourceA.
And I use the below table to understand which source to use when I am updating the Customers table:
DECLARE #temp TABLE (column_name varchar(100), source_to_use varchar(100), source_priority int)
INSERT INTO #temp
SELECT 'RepName', 'SourceA', 1 UNION ALL
SELECT 'RepName', 'SourceB', 2 UNION ALL
SELECT 'City', 'SourceB', 1 UNION ALL
SELECT 'City', 'SourceA', 2
Based on this I need to update the rep name with Tom A and city with New York based on the source_priority. Before writing the update statement I have tried to get the right rows using this:
SELECT *
FROM #diffs d
LEFT OUTER JOIN #temp t ON t.column_name = d.column_name and d.source_table = t.source_to_use
AND source_priority = CASE WHEN EXISTS
(
SELECT source_priority
FROM #temp x
Where source_priority = 1 AND d.source_table = x.source_to_use
) THEN 1 ELSE 2 END
But this does not give me what I want, is there anyway of querying these tables and update the customers table with the differences based on priority?
Thanks
One way that I can think to do this. Flatten the three tables into a single table with different columns. Then use cross apply to choose the value from #temp. Here is an example that assumes that customers has rows for all customers:
select c.ref, repname.repname
from (select c.*, ca.repname as repname_a, ca.city = city_a,
cb.repname as repname_b, cb.city as city_b
from customers c left join
customersa ca
on c.ref = ca.ref left join
customersb cb
on c.ref = cb.ref
) c cross apply
(select top 1
(case when source_to_use = 'source_a' and repname_a is not null then name_a
when source_to_use = 'source_b' and repname_b is not null then repname_b
when source_to_use = 'source' and repname is not null then repname
end) as repname
from #temp t
where t.column_name = 'repname'
order by priority
) repname;
I'd go for a CTE. Something like this should work:
WITH cte AS (
SELECT d.*, t.source_priority
FROM #diffs d
LEFT OUTER JOIN #temp t
ON t.column_name = d.column_name
AND d.source_table = t.source_to_use
), mins AS (
SELECT ref, column_name, MIN(source_priority) source_priority
FROM cte
GROUP BY ref, column_name
)
SELECT cte.ref, cte.column_name, cte.new_value
FROM cte INNER JOIN mins
ON cte.ref = mins.ref
AND cte.column_name = mins.column_name
AND cte.source_priority = mins.source_priority

SQL join to always return initial match and NULLs for subsequent mismatches

How can a join be created that will always return a row for those units in Unit that have a row in Test even when the row in test is in TestDetail with a PartID that has a row in Part with a PartFamilyID that has a row in PartFamily with a Name not equal to, in this case, B. In other words, always return a record for those units with a test record but with NULL values when the subsequent joins are false.
For example, from the code below I expected (I apologize I do not have the reputation to post images and I cannot figure out a way to post a table):
u.ID t.IDt.UnitID td.ID td.TestID td.PartID p.ID p.PartFamilyID pf.ID pf.Name
1 NULL NULL NULL NULL NULL NULL NULL NULL NULL
2 NULL NULL NULL NULL NULL NULL NULL NULL NULL
2 15 2 114 15 1115 1115 11115 11115 E
3 NULL NULL NULL NULL NULL NULL NULL NULL NULL
4 14 4 113 14 1112 1112 11114 11114 D
4 16 4 115 16 1114 1114 11115 11115 E
5 NULL NULL NULL NULL NULL NULL NULL NULL NULL
declare #Results table (UnitID int, Value varchar(10))
insert into #Results (UnitID)
values (1),(2),(3),(4),(5)
declare #Unit table (ID int)
insert into #Unit
values (1),(2),(3),(4),(5),(6),(7)
declare #Test table (ID int, UnitID int)
insert into #Test
values (11,1),(12,1),(13,2),(14,4),(15,2),(16,4)
declare #TestDetail table (ID int, TestID int, PartID int)
insert into #TestDetail
values (111,11,1111),(112,13,1111),(113,14,1112),(114,15,1115),(115,16,1114)
declare #Part table (ID int, PartFamilyID int)
insert into #Part
values (1111,11112),(1112,11114),(1113,11114),(1114,11115),(1115,11115)
declare #PartFamily table (ID int, Name varchar(10))
insert into #PartFamily
values (11111,'A'),(11112,'B'),(11113,'C'),(11114,'D'),(11115,'E')
select *
from #Unit u
left join #Test t
on t.UnitID = u.ID
join #TestDetail td
on td.TestID = t.ID
join #Part p
on p.ID = td.PartID
join #PartFamily pf
on pf.ID = p.PartFamilyID
and pf.Name <> 'B'
However, the query excludes the rows where t.ID is NULL, so only the non-NULL t.ID rows for units 2 and 4 are left.
I have tried a variety of combinations of different types of joins without success.
Ultimately, I want to use the query to update a table:
update r
set r.Value = case when t.ID is not NULL then 'Yes' else 'No' end
from #Results r
left join #Unit u
on u.ID = r.UnitID
left join #Test t
on t.UnitID = u.ID
join #TestDetail td
on td.TestID = t.ID
join #Part p
on p.ID = td.PartID
join #PartFamily pf
on pf.ID = p.PartFamilyID
and pf.Name <> 'B'
select * from #Results
Which actually works when rows are returned.
If the NULL t.ID rows were returned, I expected the case statement to evaluate to Yes when at least one row for a single unit contained a non-NULL t.ID value.
I understand that I can subsequently update #Results where Value is NULL which is fine.
However, I am still trying to understand how to get the rows for all the units to be returned.
I thought that a left join would still leave the unit even when the subsequent (inner) joins return no matches.
If a unit has a match in Test but the test record has no match in TestDetail how can I get the record for the unit (with the NULL values in the columns of the subsequent tables without a match) returned?
Thanks in advance!
you have to do left joins after the left join bec the way you do your update disables the left join of t since t.ID=null won't ever find a TestDetail td
select r.*
, r.ValueNew = case when t.ID is not NULL then 'Yes' else 'No' end
from #Results r
left join #Unit u on u.ID = r.UnitID
left join #Test t on t.UnitID = u.ID
left join #TestDetail td on td.TestID = t.ID
left join #Part p on p.ID = td.PartID
left join #PartFamily pf on pf.ID = p.PartFamilyID and pf.Name <> 'B'
this way, you will have your record r and nothing else