SQL新手,有一个查询可以通过多个表中的多个连接来提取一些数据。
示例数据:
PERSON_NAME FUNCTION_NAME FUNCTION_ID FUNCTION_GROUP
Bob View Result 1 Editor
Bob Edit Result 4 Editor
Bob Delete Result 3 Editor
Bob Email Result 8 Editor
Mary Print Letter 45 Admin
Mary Grant Access 37 Admin
函数具有ID,而function_groups具有许多函数。我想查询数据,而不是它与上面的例子类似,它看起来像:
PERSON_NAME FUNCTION_NAME FUNCTION_ID FUNCTION_GROUP
Bob View Result,Edit Result, Delete Result 1,4,3,8 Editor
Mary Print Letter,Grant Access 45,37 Admin
“鲍勃属于编辑,编辑器具有以下功能”作为一个结果,而不是初始示例,其中返回多行。
我认为独特或不同的关键字可以帮助我吗? 谢谢!
编辑:现在使用代码
select staff_member.person_name, function.function_name,staff_group_function.function_id, staff_group.function_group_name
from staff_member
inner join staff_group
on staff_group.staff_group_id=staff_group_member.staff_group_id
inner join staff_group_function
on staff_group_function.staff_group_id=staff_group_member.staff_group_id
inner join function
on function.function_id=staff_group_function.function_group_name
答案 0 :(得分:4)
不。如果你有Oracle 11g2,你需要的是LISTAGG()
。这可能是您的查询:
SELECT person_name,
LISTAGG(function_name, ', ') WITHIN GROUP (ORDER BY 1) function_name,
LISTAGG(function_id, ', ') WITHIN GROUP (ORDER BY 1) function_id,
function_group
FROM my_table
GROUP BY person_name, function_group
或者(跟随你的最新评论):
SELECT person_name,
LISTAGG(function_name, ', ') WITHIN GROUP (ORDER BY 1) function_name,
LISTAGG(function_id, ', ') WITHIN GROUP (ORDER BY 1) function_id,
LISTAGG(function_group, ', ') WITHIN GROUP (ORDER BY 1) function_group
FROM my_table
GROUP BY person_name
对于11g2之前的任何版本,这篇有趣的文章为您提供了解决方案:
http://www.oracle-base.com/articles/misc/string-aggregation-techniques.php
答案 1 :(得分:2)
UNIQUE
和DISTINCT
与分组和汇总结果无关。您必须GROUP BY
PERSON_NAME
和FUNCTION_GROUP
,然后应用自己的aggregate function对剩余结果进行分组。
这个article告诉你如何使用LISTAGG
通过Oracle中的聚合函数连接逗号字符串。
答案 2 :(得分:1)
在10g
中,它的工作原理如下
with tab as (
select 'Bob' PERSON_NAME,'View Result' FUNCTION_NAME,'1' FUNCTION_ID,'Editor' FUNCTION_GROUP from dual
union all
select 'Bob' PERSON_NAME,'Edit Result' FUNCTION_NAME,'4' FUNCTION_ID,'Editor' FUNCTION_GROUP from dual
union all
select 'Bob' PERSON_NAME ,'Delete Result'FUNCTION_NAME,'3' FUNCTION_ID,'Editor' FUNCTION_GROUP from dual
union all
select 'Bob' PERSON_NAME,'Email Result' FUNCTION_NAME,'8' FUNCTION_ID,'Editor' FUNCTION_GROUP from dual
union all
select 'Mary' PERSON_NAME,'Print Letter' FUNCTION_NAME,'45' FUNCTION_ID,'Admin' FUNCTION_GROUP from dual
union all
select 'Mary' PERSON_NAME , 'Grant Access' FUNCTION_NAME ,'37' FUNCTION_ID,'Admin' FUNCTION_GROUP from dual
)
select person_name
,wm_concat(function_name) function_name
,wm_concat(function_id) function_id
,function_group
from tab
group by person_name,function_group
<强>输出强>