SQL Server - distinct value from multiple(2) columns
suppose I have two columns of integers, A and B. Now I want distinct values from these, meaning if both A and B have 1, I want 1 only once.
Note: I am NOT interested in getting distinct rows. I just want to get unique integer values from this table which could either be in A or B
I could insert values of A and B in one column of some temp table and do a select distinct over that column.
Anything more sophisticated (perform开发者_如何学运维ancewise)?
Something like that should work, I think:
select all the distinct A's, then all the distinct B'
UNION ALL these two sets
select DISTINCT from that unionized result set
SELECT DISTINCT * FROM
(
SELECT DISTINCT A FROM YourTable
UNION ALL
SELECT DISTINCT B FROM YourTable
)
With Lukáš' help, you can simply write:
SELECT A FROM YourTable
UNION
SELECT B FROM YourTable
since as he rightfully points out, the regular UNION returns no duplicates. You don't even need to have a DISTINCT clause on your individual SELECTs - quite ingenious! Thanks, Lukáš!
Marc
精彩评论