2011-11-23 33 views
1

这是我的表:是否存在条款

ID  COUNTRY_CODE_3D  COUNTRY_CODE_2D  TYPE_ID  
1   "IND"   "IN"     11   
2   "CAN"   "CA"     13   
3   null   null     17 

我想选择查询将返回单行 如果COUNTRY_CODE_2D = 'CA'(有效数据)返回第2行,否则返回第3行,其中COUNTRY_CODE_2D =null and TYPE_ID=17

+1

你可以重新组织你的问题,因此更有感?也许显示表格的图像? – slugster

回答

2

如果你可以把country_code_2d功能指数(NVL(country_code_2d,'EMPTY')

CREATE INDEX fidx_empty_null ON country_cnfg_tbl (NVL(country_code_2d,'EMPTY')); 

,然后你可以

SELECT * FROM country_cnfg_tbl a 
WHERE NVL(a.country_code_2d,'EMPTY') IN 
( 
    SELECT NVL(b.country_code_2d,'EMPTY') FROM dual d 
    LEFT JOIN country_cnfg_tbl b on b.country_code_2d = 'CA' 
) 

或无连接(更便携,因为它不使用Oracle表DUAL

SELECT * FROM country_cnfg_tbl a WHERE NVL(a.country_code_2d,'EMPTY') IN 
(  
    SELECT CASE WHEN count(*) = 0 THEN 
       'EMPTY' 
      ELSE 
       b.country_code_2d 
      END as country_code_2d 
    FROM country_cnfg_tbl b 
    WHERE b.country_code_2d = 'CA' 
    GROUP BY b.country_code_2d 
) 
+0

感谢您的快速答复。但如果'CAA'不存在,它会返回一个包含所有空值的行,我想要一行应该从这个country_cnfg_tbl表中返回一行,该表有b.country_code_2d = null –

+0

好吧,列(已经更新了我的答案) –

+0

如果b.country_code_2d ='CAA'不存在,它应该返回同一个表中的b.country_code_2d = null的行,如果可能的话,你可以给一个没有任何连接的查询,谢谢.. –

0

例无明确连接:

SELECT 
    * 
FROM 
    country_cnfg_tbl 
WHERE 
    nvl(country_code_2d,'xxx') 
    = 
    (select nvl(country_code_2d,'xxx') 
    from country_cnfg_tbl 
    where country_code_2d='CA') 

但我向你保证,凯文·伯顿的答案是更好的:)我投它:))

1

谢谢凯文弗罗林你的帮助。

凯文,你给我的第二个查询有1个错误。但我改变了一些东西,现在它的做工精细,凯文感谢您宝贵的投入,保持良好的工作:)

这是最终的查询:

SELECT * FROM country_cnfg_tbl a WHERE NVL(a.country_code_2d,'EMPTY') IN 
(SELECT 
CASE 
WHEN (select count(*) FROM country_cnfg_tbl WHERE country_code_2d IN ('CA') OR country_code_2d IS NULL) = 1 THEN 'EMPTY' ELSE country_code_2d 
END as country_code_2d FROM country_cnfg_tbl WHERE country_code_2d IN ('CA') OR country_code_2d IS NULL);