2017-01-20 46 views
0

对不起,如果这已被问及,搜索了一下,没有找到像我以后的东西,但如果它有请链接。连接来自多个表的多列Oracle

我正在使用Oracle,并试图在不使用临时表的多个表中的多个列之间汇总结果。下面的例子:

Table: USERS 
-------------- 
ID | USER_NAME 
-------------- 
1 | Bob 
2 | Joe 
3 | Mary 

Table: PROJECT_USERS 
---------------------------------- 
USER_ID | PROJECT_ID | ACCESS_TYPE 
---------------------------------- 
1  |123   |8 
1  |456   |9 
1  |789   |10 
2  |123   |10 
2  |456   |9 
2  |789   |8 
3  |123   |9 
3  |456   |10 
3  |789   |10 

我已经能够做的事情就像找到谁是在一个特定的项目输出到一个单一的领域使用的查询,如用户使用LISTAGG一些成功:

SELECT 
    LISTAGG(users.user_name, ',') WITHIN GROUP (ORDER BY users.user_name) 
FROM 
    users, 
    project_users 
WHERE 
    project_users.user_id = users.id 
    AND project_users.project_id = 123 
GROUP BY ID 
; 

(道歉,如果语法稍微偏离在上面,模糊的实际结构和数据的原因,所以这是不是我用活准确的查询) 这将输出:

Bob,Joe,Mary 

但我想输出是USERS.USER_NAME和PROJECT_USERS.ACCESS_TYPE类似的格式汇总的组合,也许相隔两个值 -

Bob-8,Joe-10,Mary-9 

我可以得到个人回报

SELECT users.user_name || '-' || project_users.access_type... 

返回

Bob-8 
Joe-9 
Mary-10 

并希望那时我能LISTAGG这些结果,但遗憾的是一直没能到g等它工作。正如前面提到的,临时表是正确的,因为我不想进入,但我确信这会让事情变得更容易。在FROM中使用SELECT不起作用,我不认为,因为最后我希望能够在子查询中使用它,并且我的理解(以及尝试它的有限经验)是不会正确迭代的每次通过。也许我错了,只是做错了。

有什么建议吗?

谢谢!

+0

这岂不实际上是更容易,因为你在一个列表做返回的数据,而不是逗号分隔值,如果你要在一个子查询中使用它? – BobC

+0

@BobC会是理想的,但是这个被用于报告的报告笨拙地被用来解析数据并将其重新输入到别的东西中。这真的很难看,而不是我会怎么做,但最终我需要子查询返回一行来用于此。显然,正确的数据完整性标准应该被诅咒。 – CascadeOverflow

回答

0

看来你想要这样的东西。不知道为什么你想要它(在这种情况下),但它说明了你所问的方法。

with 
    users (id, user_name) as (
     select 1, 'Bob' from dual union all 
     select 2, 'Joe' from dual union all 
     select 3, 'Mary' from dual 
    ), 
    project_users (user_id, project_id, access_type) as (
     select 1, 123, 8 from dual union all 
     select 1, 456, 9 from dual union all 
     select 1, 789, 10 from dual union all 
     select 2, 123, 10 from dual union all 
     select 2, 456, 9 from dual union all 
     select 2, 789, 8 from dual union all 
     select 3, 123, 9 from dual union all 
     select 3, 456, 10 from dual union all 
     select 3, 789, 10 from dual 
    ) 
-- End of test data (not part of the SQL query). 
-- Query begins below this line. 
select project_id, 
     listagg(user_name || '-' || to_char(access_type), ',') 
      within group (order by user_name) as comma_sep_list 
from users u join project_users p on u.id = p.user_id 
group by project_id 
; 

PROJECT_ID COMMA_SEP_LIST 
---------- -------------------- 
     123 Bob-8,Joe-10,Mary-9 
     456 Bob-9,Joe-9,Mary-10 
     789 Bob-10,Joe-8,Mary-10 

3 rows selected. 
+0

太爱了!这个伎俩。不确定是否是TO_CHAR,隐含的JOIN或GROUP BY ......更有可能出现在多个位置,现在我查看了我正在尝试的内容。非常感谢! – CascadeOverflow

+1

你可能在没有'to_char()'的情况下离开,我只是不喜欢隐式转换。其余的你可能是对的。干杯! – mathguy