简体   繁体   中英

SQL Merge the row into new column

I have a table named Addresses .

The columns are:

Property | Road | Town | Borough | District | Postcode

There is no data in Property as of yet as I will update it manually later. The rest of the columns does hold data though.

However I need to merge Road, Town, Borough, District and Postcode into a new column named Full Address .

So for example

Property |    Road     |     Town     |  Borough  |  District  | Postcode | Full Address
  NULL     London Road      London       Enfield      North      EN16 5FD   NULL, London Road, London, Enfield, North, EN16 5FD

If you can see the "Full Address" column has taken everything from the same row and added it into the row itself.

How would I be able to do this within SQL?

You want string concatenation. Many databases support concat_ws() :

update mytable
set full_address = concat_ws(', ', 
    property,
    road,
    town,
    borough,
    district,
    postcode
);

The behavior on concat_ws() as regard to null values varies across databases. Some will return a null value if any value in the list is null ; in that case, you might want to surround null able columns in the list with coalesce() , as in coalesce(property, '') .

If your database does not support group_concat() , then use the regular string concatenation operator; in standard SQL, that's || :

    property    || ', '
    || road     || ', '
    || town     || ', '
    || borough  || ', '
    || district || ', '
    || postcode

Finally: it is not necessarily a good idea to store this derived information. Instead, you can use a computed column or a view:

create view myview as
select t.*,
    concat_ws(', ', 
        property,
        road,
        town,
        borough,
        district,
        postcode
    ) as full_address
from mytable t

GMB has already answered a question by using concat_ws() function, but you can also do it using CONCAT() function as below.

SELECT 
        Road, 
        Town, 
        Borough, 
        District,
        CONCAT(Road,' ', Town,' ', Borough,' ', District) as Full_Address
    FROM mytable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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