2
Good night,
Guys, I have the following problem:
I need to make a Join in two tables, USER and CONTACT. Each user has more than one contact (Phone), so when I list the data he returns me lines "duplicated" with different phones because, EX:
ID | Nome | Telefone
1 | Felipe | 968181444
1 | Felipe | 37056781
2 | Claudio | 37059999
2 | Claudio | 968899999
It is possible for me to create a dynamic phone column to list the data in this way below?
ID | Nome | Telefone 1 | Telefone 2
1 | Felipe | 968181444 | 37056781
2 | Claudio | 37059999 | 968899999
I googled a lot, I found something about PIVOT but I could not develop something similar to what I need.
Follow the query:
SELECT u.ID, u.NOME, c.TELEFONE
FROM USUARIO u INNER JOIN CONTATO c
ON c.USUARIO_ID = u.ID
ORDER BY u.NOME
Any solution to this?
Ask your question the code you have already tested to try to come up with a solution.
– João Martins
This will not be easy to do, since the number of phones is dynamic. The only way that might solve is with dynamic SQL.
– João Martins
Hi, Philippe, I was checking in here and there’s a article by Stackoverflow-EN that answers your question.
– Andre Mesquita
Try subquery, something like: SELECT u.usuario_id AS Usu , u.nome , c.telefone AS phone1, (SELECT telefone from telefone t Where t.usuario_id = u.usuario_id AND t.telefone != phone1 LIMIT 1) AS phone2 FROM usuario u INNER JOIN telefone c ON c.USUARIO_ID = u.USUARIO_ID GROUP BY u.usuario_id ORDER BY u.name
– graciomar
Search by pivot operator.
– anonimo
I got it through the graciomar tip. I put a subquerie for phone 2 to create a new column.
– Philippe Nunes
https://docs.oracle.com/cd/E11882_01/server.112/e41084/functions089.htm#SQLRF30030 , listagg creates a single column but concatenates the values , another solution and , having something that identifies making a case with max e group by
– Motta