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

2 Answers 2

4

Using union is definitely a reasonable approach to this problem. In most databases, though, the following may be faster:

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

The reason is that the table is only scanned once, rather than once for each column. This can be particularly important when tab is not really a table, but a more expensive view. (And some databases support unpivot which behaves similarly to this.)

Sign up to request clarification or add additional context in comments.

Comments

3

Try to use union with both columns

select Department1 
from tab
union 
select Department2 
from tab

NOTE: union command eliminates duplicates

2 Comments

Thank you, that was exactly what I was looking for - and learned that union eliminates duplicates.
@ElChupanibre Don't problem, but remember ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.