ZipCode查询拉五位和九位

时间:2013-10-18 20:42:07

标签: sql-server

我试图在MSSQL中提取一个查询,如果它们存在于cus_address表中的9位数字代码中。我已经从我自己创建的一个名为dbo.WEST_PALM_ZIPS的表中拉出了5位数的zipcodes。我需要拉出WEST_PALM_ZIPS表中的所有拉链以及CUS_ADDRESS.POSTAL_CODE(感谢任何帮助)

SELECT DISTINCT [Member Id] = Cust.MASTER_CUSTOMER_ID,[FirstName] = Cust.First_Name    

[Lastname] = Cust.Last_Name,

[Email] = Cust.PRIMARY_EMAIL_ADDRESS,

[Zip Code] = addr.POSTAL_CODE

FROM ORDER_DETAIL OD
INNER JOIN CUSTOMER  Cust 
    ON  Cust.MASTER_CUSTOMER_ID = OD.SHIP_MASTER_CUSTOMER_ID 
    and Cust.SUB_CUSTOMER_ID = OD.SHIP_SUB_CUSTOMER_ID 
    and od.subsystem = 'MBR'

INNER JOIN CUS_ADDRESS  Addr    
    ON Addr.CUS_ADDRESS_ID = OD.SHIP_ADDRESS_ID  
    and Addr.POSTAL_CODE in ( select POSTAL_CODE from [dbo].[WEST_PALM_ZIPS])
    and Addr.COUNTRY_descr = 'United States'
    and  If(Len([Postal_Code])>5,Left([Postal_Code],5) & "-" &
Mid([Postal_Code],6),[Postal_Code])][0-9]


INNER JOIN CUS_ADDRESS_DETAIL  AddrD 
    ON AddrD.MASTER_CUSTOMER_ID = OD.SHIP_MASTER_CUSTOMER_ID 
    and AddrD.SUB_CUSTOMER_ID = OD.SHIP_SUB_CUSTOMER_ID 
    and AddrD.CUS_ADDRESS_ID = OD.SHIP_ADDRESS_ID 
    and AddrD.ADDRESS_TYPE_CODE = OD.SHIP_ADDRESS_TYPE_CODE     

1 个答案:

答案 0 :(得分:2)

我认为这就是你所追求的 - 尽管如果我误解了任何东西/如果它不像你预期的那样工作,请大声喊叫。

SELECT DISTINCT [Member Id] = Cust.MASTER_CUSTOMER_ID
,[FirstName] = Cust.First_Name    
,[Lastname] = Cust.Last_Name
,[Email] = Cust.PRIMARY_EMAIL_ADDRESS
,[Zip Code] = addr.POSTAL_CODE
FROM ORDER_DETAIL OD

INNER JOIN CUSTOMER  Cust 
    ON  Cust.MASTER_CUSTOMER_ID = OD.SHIP_MASTER_CUSTOMER_ID 
    and Cust.SUB_CUSTOMER_ID = OD.SHIP_SUB_CUSTOMER_ID 
    and od.subsystem = 'MBR'

INNER JOIN CUS_ADDRESS  Addr    
    ON Addr.CUS_ADDRESS_ID = OD.SHIP_ADDRESS_ID  
    and Addr.COUNTRY_descr = 'United States'
    --check for 5 digit or 9 digit zip codes
    and 
    (
        --check for 5 digit zip codes based on contents of table
        (
            LEN(Addr.POSTAL_CODE) = 5
            and Addr.POSTAL_CODE in 
            ( 
                select POSTAL_CODE 
                from [dbo].[WEST_PALM_ZIPS] wpz
                --if you want to be sure you only get the 5 digit codes from this table (though from your description I believe that's all this table contains?)
                --where LEN(POSTAL_CODE) = 5
                --and Addr.POSTAL_CODE like '[0-9][0-9][0-9][0-9][0-9]'
            )
        )
        or -- check that it's a 9 digit code
        (
            LEN(Addr.POSTAL_CODE) = 10
            and SUBSTRING(Addr.POSTAL_CODE,6,1) = '-'   
            and Addr.POSTAL_CODE like '[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'
        )
    )
INNER JOIN CUS_ADDRESS_DETAIL  AddrD 
    ON AddrD.MASTER_CUSTOMER_ID = OD.SHIP_MASTER_CUSTOMER_ID 
    and AddrD.SUB_CUSTOMER_ID = OD.SHIP_SUB_CUSTOMER_ID 
    and AddrD.CUS_ADDRESS_ID = OD.SHIP_ADDRESS_ID 
    and AddrD.ADDRESS_TYPE_CODE = OD.SHIP_ADDRESS_TYPE_CODE   

有关上述示例中使用的类似语句/模式匹配的说明,请参阅http://msdn.microsoft.com/en-us/library/ms187489(SQL.90).aspx