[英]How to convert Multiple row values to one row with comma-separated value different ID in Oracle
我正在嘗試使用以下查詢以逗號分隔值返回數據。
select u.employeeid,
( select name
from roles r
where r.id = ur.role_id
) userrole
from users u,
user_role ur
where u.id in (select DISTINCT ur.user_id
from user_role ur)
order by u.employeeid asc;
當前 Output:
EMPLOYEEID USERRROLE
---------------------
1000 ROLE_SUPER_ADMIN
1000 ONBOARDING_CHECKER
1000 ROLE_SUPER_ADMIN
1000 ROLE_APPROVER
1000 ROLE_ONBORDING
現在,當我執行查詢時,我希望表如下:
EMPLOYEEID USERRROLE
--------------------
1000 ROLE_SUPER_ADMIN,ONBOARDING_CHECKER,ROLE_SUPER_ADMIN,ROLE_APPROVER,ROLE_ONBORDING
使用LISTAGG
(和 ANSI 連接,而不是傳統的逗號連接和令人困惑的子查詢)。 你可能想要的是:
SELECT u.employeeid,
LISTAGG( r.name, ',' ) WITHIN GROUP ( ORDER BY r.name ) AS userrole
FROM users u
INNER JOIN user_role ur
ON ( u.id = ur.user_id )
LEFT OUTER JOIN roles r
ON ( r.id = ur.role_id )
GROUP BY u.employeeid
ORDER BY u.employeeid asc;
雖然我認為你實際寫的是:
SELECT u.employeeid,
LISTAGG( r.name, ',' ) WITHIN GROUP ( ORDER BY r.name ) AS userrole
FROM users u
CROSS JOIN user_role ur
LEFT OUTER JOIN roles r
ON ( r.id = ur.role_id )
WHERE EXISTS ( SELECT 1
FROM user_roles x
WHERE u.id = x.user_id )
GROUP BY u.employeeid
ORDER BY u.employeeid asc;
這會做:
SELECT LISTAGG("USERRROLE", ',') WITHIN GROUP (ORDER BY "USERRROLE")
FROM Table1 group by "EMPLOYEEID";
檢查小提琴: http://sqlfiddle.com/#!4/d11c6/4
謝謝!!!!!!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.