我想为sql表中的每一列选择所有不同的

时间:2016-10-17 17:11:52

标签: sql

country     state   city    
Country1    state1  city5   
Country2    state2  city6   
Country5    state1  city6   
Country5    state3  city6   
Country2    state3  city9   

我希望从国家/地区,州,城市获取不同的值,并且所有这些列都不应为空。我尝试了几个查询但不起作用..输出应该是所有不同的值,如下所示

Country1    
Country2    
Country5    
state1
state2
state3
city5
city6
city9

1 个答案:

答案 0 :(得分:2)

简单方法是使用UNION

Select country from yourtable
Union
Select state from yourtable
Union 
Select city from yourtable

如果DBMS支持APPLY运营商

,则可以轻松完成此操作
SELECT datas
FROM   Youtable s
       CROSS apply (SELECT [country] UNION
                    SELECT [state] UNION
                    SELECT [city]) cs (datas) 

如果您的DBMS支持LATERAL,那么(感谢a_horse_with_no_name)

select t.x
from the_table
  cross join lateral (select country union select state union select city ) as t(x)
order by t.x