I am working in SQL, I have 3 tables as you can see in the image, in the TipoAddressEntidad table I have if it is email or home address, what I require is to show the name (in entity), the email address and the home address.
I have the code separately but I need it to return 4 columns: ID, Name, Address, Email, in a single query. I hope you can understand and help me
select distinct en.Id, en.Nombre, de.Nombre Direccion from Persona.Entidad as en
inner join Persona.DireccionEntidad as de on de.EntidadId=en.Id
where de.TipoDireccionEntidadId=1
select distinct en.Id, en.Nombre, de.Nombre Email from Persona.Entidad as en
inner join Persona.DireccionEntidad as de on de.EntidadId=en.Id
where de.TipoDireccionEntidadId=2
You can do it in various ways.
For the scenario I am not going to use the Person schema and directly use the dbo.
One option is to use a
Left join
and apply the join pattern to it.This way you can relate several times, giving them a different alias, to each of the tables.
You have to take into account that if a person has several emails or addresses, you will have repeated person rows.
But if you add another address for Ana then, to which address is each of her emails given?
Operator Apply Option
When you only want one, you can use the apply operator.
Within the sets that are in parentheses, and that only return one result for each id of the outer set, you have an order by to specify which one you prefer.
Apply operator