当我在查询的ELSE部分尝试使用listagg选择语句时,出现 ORA-00937 错误。有什么方法吗?
select
CASE
when count(*) = 0 then
'There are no users connected'
else
(select
listagg(osuser, ', ') within group (order by osuser)
from (select distinct osuser from v$session)
where osuser != 'SYSTEM' and osuser not like 'VMCONFTEST%')
end
from v$session
where username is not null
and osuser not like 'VMCONFTEST%';
即使我用更简单的东西替换select语句,例如select osuser from v$session
,我也会得到同样的错误。
答案 0 :(得分:4)
采取略有不同的方法但似乎有效。 不要套管并进行计数,只需检查聚合是否为空(coalesce返回系列中的第一个非空值),以及它是否替代了您的消息。这避免了我认为不需要的第二级分组。
太糟糕的listagg也不支持聚合中的不同;我们可以避免内联视图。
SELECT coalesce(listagg(A.osuser, ', ') within group (order by A.osuser),
'There are no users connected') as userList
FROM (select distinct osuser from v$session) A
WHERE A.osuser!= 'SYSTEM' and A.osuser not like 'VMCONFTEST%'
这确实存在开销,因为它试图生成您的case语句可能试图短路的用户列表。但是,如果V $ session中没有记录,则select distinct应该很快。
虽然说实话但我不确定为什么我们需要这样做。列表中的空值通常是足够的响应,表示没有用户。 UI将处理null意味着没有用户。
如果我们更多的内联视图的where子句,可能会更快..
SELECT coalesce(listagg(A.osuser, ', ') within group (order by A.osuser),
'There are no users connected') as userList
FROM (SELECT distinct osuser
FROM v$session
WHERE A.osuser!= 'SYSTEM'
and A.osuser not like 'VMCONFTEST%') A
答案 1 :(得分:1)
您的陈述缺少group by子句,例如下面有效:
select distinct(
CASE
when count(*) = 0 then
'There are no users connected'
else
(select
listagg(osuser, ', ') within group (order by osuser)
from (select distinct osuser from v$session)
where osuser != 'SYSTEM' and osuser not like 'VMCONFTEST%')
end)
from v$session
where username is not null
and osuser not like 'VMCONFTEST%'
GROUP BY osuser;
答案 2 :(得分:0)
select
CASE
when cnt = 0 then
'There are no users connected'
else
(select
listagg(osuser, ', ') within group (order by osuser)
from (select distinct osuser from v$session) t
where osuser != 'SYSTEM' and t.osuser not like 'VMCONFTEST%')
end result
from
(select count(*) as cnt
from v$session
where username is not null
and osuser not like 'VMCONFTEST%');
答案 3 :(得分:0)
with conn_users as
(select count(*) conn_users
from v$session
where osuser != 'SYSTEM'
and osuser not like 'VMCONFTEST%'),
aggr_users as
(select listagg(osuser, ', ') within group (order by osuser)
from (select distinct osuser from v$session)
where osuser != 'SYSTEM' and osuser not like 'VMCONFTEST%')
select
CASE
when (select * from conn_users) = 0 then
'There are no users connected'
else
(select * from aggr_users)
end
from dual;
问题是无法忍受的计数
在我需要执行复杂子查询时,我喜欢使用with子句 可能这个查询可以改进集中条件(重复)