Sql查询仅在count(列)= 1时选择记录

时间:2014-03-18 06:00:37

标签: sql oracle10g case

我正在尝试从oracle 10g express中检索记录。

我想执行:

select name|| '=' || id from literals where name='vge_1'

仅当count(vge_1)等于1时才<。

否则我想显示错误。

我尝试了以下查询,但是给出了

ORA-00905: missing keyword

我尝试的查询如下:

select case(name) 
when count('vge_1') then (select name|| '=' || id from literals where name='vge_1';)
else Errror 
end
from Literals where name='vge_1';

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

而不是case在查询末尾添加HAVING count(name)=1

答案 1 :(得分:1)

试试这个:

select b.id,a.* from
(select name from Literals 
where name='vge_1'
group by name
having count(name)=1)a,Literals b
where b.name=a.name

答案 2 :(得分:0)

试试这个SQL Fiddle

select distinct case 
    when l2.c = 1 then l1.name || '=' || l1.id
    else 'Error'
end as name_id
from literals l1,
(
    select name, count(name) as c
    from literals
    where name = 'vge_1'
    group by name
    having count(name) = 1
) l2
where l1.name = l2.name(+)
and l1.name = 'vge_1'
;

内部查询与其他答案大致相同。外部查询使用左外部联接(+)来确定内部查询是否包含count()限制的匹配项。

请注意,运行此查询时必须在两个位置更新名称。