如何使用T-sql将一列拆分为多个列

时间:2016-11-11 18:38:17

标签: sql-server tsql

enter image description here

ID  NAME         Address1                    Address2
1   kjp     Station raod anand                 NULL
2   Roma    7000 ny street ny 21075            NULL
3   rony    5001 oak tree st jessup 21005      NULL

我希望结果像

ID  NAME         Address1        Addres2    postalcode
1   kjp     Station raod           Anand     NULL
2   Roma    7000 ny street         ny        21075  
3   rony    5001 oak tree st       jessup    21005

2 个答案:

答案 0 :(得分:1)

解析地址可能很棘手。

一种选择是使用GOOGLE API自动化流程对地址进行地理编码,解析JSON结果以返回更标准化的结果。这可能非常耗时,但您对数据更有信心。

https://maps.googleapis.com/maps/api/geocode/json?address=1600%20Pennsylvainia%20Ave,%20Washington%20DC

答案 1 :(得分:0)

  • find 一个按空格分割字符串的函数。
  • 使用 REVERSE 找出每个字符串的最后两个字。
  • 检查[last][beforeLast]
    • 可以计算从[Addres1]
    • 中删除的字符数
    • 可以确定[last]是否为数字,则表示[beforeLast] [Address2]其他明智[last][Address2]
    • 可以确定[last]是否为数字,然后我有一个邮政编码。

<强> SQL DEMO

WITH lastToken as (
    SELECT [ID], 
           ( SELECT REVERSE(s)
             FROM  dbo.SplitString(REVERSE(Address1), ' ')
             WHERE zeroBasedOccurance = 0
           ) as last,
           ( SELECT REVERSE(s)
             FROM  dbo.SplitString(REVERSE(Address1), ' ')
             WHERE zeroBasedOccurance = 1
           ) as beforeLast
   FROM T1
)    
SELECT T1.ID, T1.Name, 
       LEFT(T1.[Address1], 
            LEN([Address1]) -
            CASE WHEN ISNUMERIC(last) = 1
                 THEN LEN(last) + LEN(beforeLast) + 2
                 ELSE LEN(last) + 1 
            END
           ) [Address1],
       CASE WHEN ISNUMERIC(last) = 1
            THEN beforeLast
            ELSE last
       END as [Address2],       
       CASE WHEN ISNUMERIC(last) = 1 
            THEN last
       END as [zipcode], 
       T2.*       
FROM T1
JOIN lastToken T2
  ON T1.[ID] = T2.[ID];

<强>输出

enter image description here