在特定SQL查询中返回1或0

时间:2013-02-08 10:06:27

标签: sql oracle oracle-sqldeveloper

表MYTABLE(ID,NUM,NAMES)中有三列。有一个列NAMES。我需要检查NAMES列以查看第一个名称是JACK还是BRUCE,并且相应的NUM列= 0.如果找到匹配,则返回1,否则为0.

ID NUM NAMES    
1  1   'TOM'
2  1   'MIKE'
3  0   'JACK'
4  1   'MICKY'
5  0   'BRUCE'

我提出了以下问题:

select *
  case NAMES in ('JACK', 'BRUCE') and NUM=0 then 1 else 0 end as MYNAMES
from MYTABLE;

不幸的是,这不起作用。

3 个答案:

答案 0 :(得分:3)

select  case
        when exists
        (
        select  *
        from    YourTable
        where   name in ('JACK', 'BRUCE')
                and NUM = 0
        )
        then 1
        else 0
        end
from    dual

Live example at SQL Fiddle.

答案 1 :(得分:1)

这有效(SQLFiddle demo):

SELECT id, num,
    CASE WHEN names IN ('JACK', 'BRUCE') AND num=0
    THEN 1 ELSE 0 END AS mynames
FROM mytable

答案 2 :(得分:0)

select case when NAMES in ('JACK','BRUCE') AND NUM = 0
            then 1
            else 0
       end
from your_table