2017-01-20 58 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