1

For example, I have the following table:

UserId Department1 Department2
------------------------------
1      Sales       Marketing
2      Research
3      Sales

And I want to get the following Results

DistinctDepartments
-------------------
Sales
Marketing
Research

I found lots of solutions that show me the distinct combined values of multiple columns, but I need the overall distinct values, as if all values would be in the same column.

Thankyou

Chris

4

2 回答 2

4

使用union绝对是解决这个问题的合理方法。但是,在大多数数据库中,以下可能会更快:

select distinct (case when n = 1 then Department1 else Department2 end)
from tab cross join
     (select 1 as n union all select 2) n

原因是表只被扫描一次,而不是每列一次。tab当不是真正的表格而是更昂贵的视图时,这一点尤其重要。(并且一些数据库支持unpivot的行为与此类似。)

于 2013-07-23T10:47:05.457 回答
3

Try to use union with both columns

select Department1 
from tab
union 
select Department2 
from tab

NOTE: union command eliminates duplicates

于 2013-07-23T10:44:22.850 回答