简体   繁体   中英

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 (performancewise)?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM