4
My friends, good night! I need to perform a query in a database using SQL Server and I got stuck in a problem so I ask, please help from you.
Here is an example summary of the problem:
- I have a table that contains the names of people (I will call TABLE 1);
- I have a table that groups certain people in TABLE 1 and establishes who is the main person and who are the secondary of this grouping (I will call TABLE 2);
TABLE 1 looks like this:
IdP Nome
1 João
2 Maria
3 José
TABLE 2 looks like this:
IdG IdP Prcp
1 1 1
1 2 0
1 3 0
That is, in this example, the 3 people are grouped in the same group and John is the main and the others are secondary... I would like to build a query that returns:
Nome NomePrincipal
João João
Maria João
José João
I tried the following query, but unsuccessfully:
select T1.Nome as 'Nome', T1P.Nome as 'NomePrincipal' from TABELA2 T2
inner join TABELA1 T1 on T2.IdP = T1.IdP
left join TABELA1 T1P on T2.IdP = T1P.IdP AND T2.Prcp = 1
I’m getting the following result:
Nome NomePrincipal
João João
Maria NULL
José NULL
Thank you!