开发者

How to join different columns of same table?

Suppose I have one table with two column, Country and City开发者_C百科.

Country

USA
Canada
UK

City

NY
London

I want to join/merge both column records and expect the output like this -

USA
Canada
UK
NY
London

So, what will be the SQL query to merge different columns records of same table?


SELECT Country FROM TABLE
UNION
SELECT City FROM Table

should do it.


Responding to the comment "I am searching for any quick way. Because if I need to merge 10 columns then i have to write 10 Unions! Is there any other way?":

You can use an unpivot, which means you just need to add the column names into a list. Only thing is to watch for data types though. eg:

--CTE for example only
;WITH CTE_Locations as (
    select Country = convert(varchar(50),'USA'), City = convert(varchar(50),'NY')
    union select Country = 'Canada', City = 'Vancouver'
    union select Country = 'UK', City = 'Manchester'
)
--Select a list of values from all columns
select distinct
    Place
from
    CTE_Locations l
    unpivot (Place for PlaceType in ([Country],[City])) u
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜