SQL串联地址

时间:2018-10-15 20:24:14

标签: sql sql-server formatting

我需要弄清楚如何以以下格式连接邮件地址:

address1 address 2 (sometimes not present) city state zip5 - zip4 (sometimes not present

我尝试从网上找到的示例进行此操作:

Stuff(  
    Coalesce(' ' + Buyer_Address1, '') + 
    Coalesce(' ' + Buyer_Address2, '') + 
    Coalesce(' ' + Buyer_City, '') + 
    Coalesce(' ' + Buyer_State, '') + 
    Coalesce(' ' + Buyer_ZipFive, '') +
    Coalesce('-' + Buyer_ZipFour, ''), 1, 1, '') AS [MailingAddress]

这些地址:

Address 1               Address 2   City    State   Zip
210 Independence Blvd               Tucson  AZ  85641
1 Palace Lane           Suite A     Toad Kingdom    FL  37058
123 Star Lane                       Star Kingdom    OH  54678

但是结果是:

210 Independence Jr Blvd Tucson AZ 85641-
1 Palace LaneSuite A Toad Kingdom FL 37058-
123 Star Lane Star Kingdom OH 54678-

解决这些问题的任何帮助都会很棒。

谢谢。

3 个答案:

答案 0 :(得分:1)

好像您的空数据为空白而不是null,因此合并将无法完成任务。而是尝试:

Stuff(  
    Coalesce(' ' + Buyer_Address1, '') + 
    --Coalesce(' ' + Buyer_Address2, '') + 
    case when coalesce(Buyer_Address2,'') <> '' then ' ' + Buyer_Address2 else '' end +
    Coalesce(' ' + Buyer_City, '') + 
    Coalesce(' ' + Buyer_State, '') + 
    Coalesce(' ' + Buyer_ZipFive, '') +
    --Coalesce('-' + Buyer_ZipFour, '')
    case when coalesce(Buyer_ZipFour,'') <> '' then '-' + Buyer_ZipFour else '' end
    , 1, 1, '') AS [MailingAddress]

答案 1 :(得分:1)

只需使用CONCAT功能...

SELECT 
    CONCAT(mt.Address1 + ' ', mt.Address2 + ' ', mt.City + ' ', mt.State + ' ', mt.ZipFive, '-' + mt.ZipFour)
FROM 
    dbo.MyTable mt;

答案 2 :(得分:1)

您的import pandas as pd df = pd.read_csv('path_to_your_csv') your_dict = df.to_dict() 似乎是空字符串,而不是to_dict。如果是这样,这应该做您想要的:

Buyer_ZipFour

根据您的示例结果,其余字段似乎没有出现此问题。