简体   繁体   English

SQL从多个列中选择单个不同的值(非组合值)

[英]SQL select single distinct values from multiple columns (not combined values)

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 克里斯

Using union is definitely a reasonable approach to this problem. 使用union肯定是解决此问题的合理方法。 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. tab不是真正的表,而是更昂贵的视图时,这尤其重要。 (And some databases support unpivot which behaves similarly to this.) (并且某些数据库支持unpivot ,其行为与此类似。)

Try to use union with both columns 尝试对两个列使用union

select Department1 
from tab
union 
select Department2 
from tab

NOTE: union command eliminates duplicates 注意: union命令消除重复项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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