I’m trying to get a query to compare two tables by LEFT OUTER JOINing the two and finding any results that don’t have a match in the right table. Problem is I have a composite key of TicketNo, ItemNo and UniqueID, and I need to only compare rows that have the highest UniqueID for any given TicketNo.
I need the data so my program knows whether it needs to update a Working copy table and what rows it needs to update if so.
Basically what I want is this:
SELECT TicketNo
FROM History t1
LEFT OUTER JOIN Working t2 on
max(t1.[UniqueID])=t2.[UniqueID]
AND t1.[TicketNo]=t2.[TicketNo]
AND t1.[ItemNo]=t2.[ItemNo]
WHERE t2.[TicketNo] IS NULL
But I can’t use the aggregate function max here. I don’t know how I can use a subquery (or failing that a CTE, but I would prefer a subquery) to get only the max unique ID for a given TicketNo. I can’t only join on the highest uniqueID in the table.
My data looks like this, assuming two duplicates:
TicketNo UniqueID ItemNo
15 1270662207 1
15 1184857061 1
In this case I only want the first row to return. I don’t care if my Working table has the old rows with TicketNo 15 or not.
Results: