How do I perform a DISTINCT operation on a single column after a UNION is performed?
T1
--
ID Value
1 1
2 2
3 3
T2
--
ID Value
1 2
4 4
5 5
I am trying to return the table:
ID Value
1 1
2 2
3 3
4 4
5 5
I tried:
SELECT DISTINCT ID, Value
FROM (SELECT*FROM T1 UNION SELECT*FROM T2) AS T3
This does not seem to work.
As far as I can say, there’s no “one-column
distinct“:distinctis always applied to a whole record (unless used within an aggregate likecount(distinct name)). The reason for this is, SQL cannot guess which values ofValueto leave for you—and which to drop. That’s something you need to define by yourself.Try using
GROUP BYto ensureIDis not repeated, and any aggregate (hereMIN, as in your example it was the minimum that survived) to select a particular value ofValue:Should be exactly what you need. That is, it’s not the same query, and there’s no
distinct—but it’s a query which would return what’s shown in the example.