Hi Team
Please refer to Live SQL link for re-producible data.
Fetch info about departments assigned to users:
SELECT user_login, dept_id, dept_name
FROM users, dept
WHERE users.user_key=dept.user_key;
USER_LOGIN DEPT_ID DEPT_NAME
------------- ---------- --------------
User1 1 Physics
User1 2 Maths
User2 3 Physics
User2 4 Maths
I would like to present output in below format.
USER_LOGIN DEPT_ID_1 DEPT_NAME_1 DEPT_ID_2 DEPT_NAME_2
------------- ------------ ------------ ----------- -------------
User1 1 Physics 2 Maths
User2 3 Physics 4 Maths
This is throwing me "ORA-00918: column ambiguously defined" exception.
select user_login,
max( decode(rn,1,dept_id) ) c1_1,
max( decode(rn,1,dept_name) ) c2_1,
max( decode(rn,2,dept_id) ) c1_2,
max( decode(rn,2,dept_name) ) c2_2
from (
select users.user_login,
dept.dept_id,
dept.dept_name,
row_number() over (partition by user_login order by rowid) rn
from users
JOIN dept ON users.user_key=dept.user_key
)
group by user_login;
Thanks!
The problem is here:
row_number() over (
partition by user_login
order by rowid
)
You've accessed two tables. The database doesn't know which one to get the rowid from!
You can fix this by prefixing rowid with the name/alias for one of the tables.
But ordering by rowid is a bad idea. It's better to pick a real column in the table. And you can use the pivot clause, saving you from typing all those max expressions:
with rws as (
select users.user_login,
dept.dept_id,
dept.dept_name,
row_number() over (
partition by user_login
order by dept_id
) rn
from users
JOIN dept
ON users.user_key=dept.user_key
)
select * from rws
pivot (
max(dept_id) id, max (dept_name) name
for rn in ( 1, 2 )
);
USER_LOGIN 1_ID 1_NAME 2_ID 2_NAME
User1 1 Physics 2 Maths
User2 3 Physics 4 Maths
If you want to know more about this, see
https://blogs.oracle.com/sql/how-to-convert-rows-to-columns-and-back-again-with-sql-aka-pivot-and-unpivot