具有多个CASE条件的SQL COALESCE未使用IS NULL返回正确的数据

时间:2014-07-18 02:09:00

标签: sql sql-server sql-server-2008

我有四个表AG_AGENTS, Px_PAXWEB, vw_POSTCODE, vwPXPaxWeb,字段为AG_AGENTS.SALES_AREA_DESC, Px_Paxweb.COUNTRY, vwPxPaxweb.SALES_AREA, vw_POSTCODE.POSTCODE

我的查询返回除

之外的所有正确值
  1. When AG_AGENTS ='Dom. -NAT', if Px_PaxWeb.COUNTRY <> 'AUT' then vwPxPaxWeb.SALES_AREA ( returning correct value till here) if vwPxPaxWeb.SALES_AREA IS NULL Then AG_AGENTS.SALES_AREA_DESC
  2. When AG_AGENTS ='Dom. -NAT', if Px_PaxWeb.COUNTRY ='AUT' Then vw_POSTCODE.POSTCODE( returning correct value till here) if vw_POSTCODE.POSTCODE IS NULL Then AG_AGENTS.SALES_AREA_DESC
  3. 基本上不返回AG_AGENTS.SALES_AREA_DESC when vw_POSTCODE.POSTCODE IS NULL and not returning AG_AGENTS.SALES_AREA_DESC when vwPxPaxWeb.SALES_AREA IS NULL

    我的SQL查询如下

    CASE WHEN AG_AGENTS.SALES_AREA_DESC = 'Dom. - NAT' 
    THEN (
        CASE WHEN PX_PAXWEB.COUNTRY = 'AUT' THEN vw_POSTCODE.POSTCODE
             WHEN PX_PAXWEB.COUNTRY <> 'AUT' THEN vwPxPaxWeb.SALES_AREA
             ELSE COALESCE (vw_POSTCODE.POSTCODE,vwPxPaxWeb.SALES_AREA,AG_AGENTS.SALES_AREA_DESC) END
    )
    ELSE 
    (
        CASE WHEN AG_AGENTS.SALES_AREA_DESC = 'Int. – Inbound' Then vwPxPaxweb.SALES_AREA
             ELSE COALESCE( vwPxPaxweb.SALES_AREA,AG_AGENTS.SALES_AREA_DESC) END
    )
    END AS SALES_AREA_DESC_2
    

2 个答案:

答案 0 :(得分:1)

我试着按照你的描述。两者似乎都是用ISNULL解决的(如下所示)。但你说这不起作用吗?

CASE WHEN AG_AGENTS.SALES_AREA_DESC = 'Dom. - NAT' 
     THEN CASE
          WHEN PX_PAXWEB.COUNTRY = 'AUT' 
          THEN ISNULL(vw_POSTCODE.POSTCODE, AG_AGENTS.SALES_AREA_DESC) --#2 fix
          WHEN PX_PAXWEB.COUNTRY <> 'AUT' 
          THEN ISNULL(vwPxPaxWeb.SALES_AREA,AG_AGENTS.SALES_AREA_DESC) --#1 fix
          ELSE COALESCE (vw_POSTCODE.POSTCODE,vwPxPaxWeb.SALES_AREA,AG_AGENTS.SALES_AREA_DESC)
          END
     ELSE CASE
          WHEN AG_AGENTS.SALES_AREA_DESC = 'Int. – Inbound'
          THEN vwPxPaxweb.SALES_AREA
          ELSE COALESCE(vwPxPaxweb.SALES_AREA,AG_AGENTS.SALES_AREA_DESC) 
          END
     END AS SALES_AREA_DESC_2

答案 1 :(得分:0)

试试这个:

CASE AG_AGENTS.SALES_AREA_DESC
    WHEN 'Dom. - NAT' THEN
    (
        COALESCE(CASE 
                    WHEN PX_PAXWEB.COUNTRY = 'AUT' THEN vw_POSTCODE.POSTCODE
                    WHEN PX_PAXWEB.COUNTRY <> 'AUT' THEN vwPxPaxWeb.SALES_AREA END,
                 AG_AGENTS.SALES_AREA_DESC)
    )
    WHEN 'Int. – Inbound' THEN vwPxPaxweb.SALES_AREA
    ELSE COALESCE(vwPxPaxweb.SALES_AREA,AG_AGENTS.SALES_AREA_DESC)
END AS SALES_AREA_DESC_2