我在oracle数据库中有3个表。他们是这样的:在where子句中使用listagg生成的列
Table User:
username|forename|surname
a a a
b b b
c c c
Table Right:
username|organisationname|right
a x user
a x admin
a x owner
a y user
a y admin
a z owner
b x user
c y user
c y admin
c z user
Table Organisation:
organisationname|number
x 12
y 14
z 42
表Right
有两个foreign_keys:username
点具有相同名称的表user
和organisationname
表Organisation
列。
对于在organisation
x上有合适用户的所有user
,我想获得用户拥有1个或更多权限的所有organisations
(组织x除外)的列表。
在我的示例中: a在x上有正确的用户,b在x上有正确的用户,c在x上没有正确的用户。 所以我只想为用户a和b(而不是c!)获得所有组织(独特!,无组织名称两次)。 如果一个用户对x以外的其他组织没有权利(他必须拥有合适的用户),我希望该用户在输出中但没有组织。
的预期结果是:
user|organisations
a y; z
b
我希望你明白我的意思。 我的查询到目前为止是这样的:
select username,
/* listagg put all the organisationnames of one user in one column separated by ;
then the organsation x gets removed from the result*/
regexp_replace (listagg (organisationname, '; ')
within group (order by organisationname), '(^x;?)|(?x;)|(; x$) ', '') as "organisations"
from(
select u2.username as username,
o.organisationname as organisationname,
/*I do this to remove duplicate entries in the list of organisations of one user */
row_number() over (partition by u2.username, o.organisationname order by u2.username) as rn
from RIGHT r2, ORGANISATION o, USER u2
where r2.organisationname = o.organisationname
and r2.username = u2.username
and r2.username IN
(
select u.username
from USER u, right r
where r.username = u.username
and r.right = 'user'
)
order by u2.username, o.organisationname
)
where rn = 1
group by username
该查询工作,但现在我想在列组织进行筛选。但是我无法在where子句中使用它。当我尝试使用它时,oracle会抛出错误: ORA-00904:无效标识符
有谁知道我该如何实现这一目标?我认为oracle由于分析函数listagg而存在问题。 我也很乐意提出如何简化查询的建议。谢谢!
这里是我试图使用列组织在where子句中:
select * from (***long query shown above***)
where organisations like '%termToSearch%';
你能也发帖,你目前在尝试什么,这给你的错误 –
我把问题的末尾where-clause查询 – Markus