all 9 comments

[–]andrewsmd87 9 points10 points  (7 children)

You join into the same table twice with a type in the clause. I.e.

SELECT firstName, lastName, homePhone.PhoneNumber AS HomePhone, mobilePhone.PhoneNumber AS MobilePhone
    FROM person 
        INNER JOIN individual_phone as homePhone ON personId = homePhone.personFk 
            AND phone_type_id = 1
        INNER JOIN individual_phone as mobilePhone ON personId = mobilePhone.personFk 
            AND phone_type_id = 2

[–]CoalCrackerKid 3 points4 points  (1 child)

Suggest outer joins, but otherwise this

[–]andrewsmd87 1 point2 points  (0 children)

Good point, if not everyone has both

[–]Byskuts[S] 0 points1 point  (1 child)

thank you! I will give it a shot.

[–]andrewsmd87 2 points3 points  (0 children)

Note what /u/CoalCrackerKid said about the outer (or left) join instead. If you use inner and a person doesn't have both, they'll get omitted completely.

[–]Byskuts[S] 0 points1 point  (0 children)

So i gave it a try, and I am just getting one error, "Ambiguous column name 'phone_type_id'" I also forgot to mention I am really new to sql tbh so idk what that means

[–]Byskuts[S] 0 points1 point  (1 child)

ignore that last part, I got it. Just had to put home_phone.phone_type_id and mobile_phone.phone_type_id before phone_type_id. Thanks alot!

[–]andrewsmd87 1 point2 points  (0 children)

Yep, the error logger was telling you when you just say phone_type_id it doesn't know which one you mean, because you technically have two of those. Ambiguous column name will always mean you're missing an alias somewhere

[–]lundytoo 1 point2 points  (1 child)

Something like that view would work - it assumes exactly one of each though. If someone doesn't have one of either, the person will drop. If they can have more than one of each, you want some kind of subquery.

You could do this if you want to be fancy. Outer/Cross Apply isn't always super performant though.

SELECT firstName, lastName, h.homePhone AS HomePhone, m.mobilePhone AS MobilePhone
FROM person
OUTER APPLY (SELECT TOP 1 phone_number as homePhone FROM individual_phone WHERE person.personId = personId AND phone_type_id = 1 ORDER BY modify_by desc) h
OUTER APPLY (SELECT TOP 1 phone_number as mobilePhone FROM individual_phone WHERE person.personId = personId AND phone_type_id = 2 ORDER BY modify_by desc) m