I'm using an UNION
to merge the results of an exact and a fuzzy search. I want the exact matches to be at the top, and the other results sorted by a column. I found this solution which works fine with UNION ALL
, but through adding the rank
column I lose the property of UNION
(without all) to remove the exact match duplicates from the result set.
Is there an elegant way to solve this, or do I have to manually remove the duplicates?
For reference, my simplified query:
SELECT 1 AS [Rank], [CallerID]
FROM [PHONE]
WHERE [CallerID] = '12345'
UNION
SELECT 2 AS [Rank], [CallerID]
FROM [PHONE]
WHERE [CallerID] LIKE '12%' AND ABS(LEN([CallerID]) - LEN('12345')) < 3
ORDER BY [Rank] ASC, [CallerID] ASC
Result could looke like this:
Rank CallerID
----------- --------------------
1 12345
2 123
2 1233
2 1234
2 12345 <- I don't want this line
2 1236
Remark: setting DISTINCT
for my CallerID won't solve the problem, since my real query has more columns. I really only want to remove duplicates between the two result sets i combine throught the UNION
.