簡體   English   中英

SQL 將行合並到新列

[英]SQL Merge the row into new column

我有一個名為Addresses的表。

這些列是:

Property | Road | Town | Borough | District | Postcode

Property中目前還沒有數據,稍后我將手動更新它。 列的 rest 確實保存數據。

但是,我需要將Road, Town, Borough, DistrictPostcode合並到一個名為Full Address的新列中。

例如

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

如果您可以看到“完整地址”列已從同一行中取出所有內容並將其添加到行本身中。

我怎樣才能在 SQL 內做到這一點?

你想要字符串連接。 許多數據庫支持concat_ws()

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

concat_ws()關於null值的行為因數據庫而異。 如果列表中的任何值是null ,有些將返回null值; 在這種情況下,您可能希望用coalesce()包圍列表中的null列,如coalesce(property, '')

如果您的數據庫不支持group_concat() ,則使用常規字符串連接運算符; 在標准 SQL 中,這是|| :

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

最后:存儲此派生信息不一定是個好主意。 相反,您可以使用計算列或視圖:

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

GMB 已經使用concat_ws() function 回答了一個問題,但您也可以使用CONCAT() function 來回答問題,如下所示。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM