0

我试图在 MSSQL 中提取一个查询,以从 cus_address 表中提取它们是否存在 9 位邮政编码。我已经从我自己创建的名为 dbo.WEST_PALM_ZIPS 的表中提取了 5 位数的邮政编码。我需要拉出我的 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     
4

1 回答 1

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 。

于 2013-10-18T21:04:33.317 回答