SQL Server - INNER JOIN WITH DISTINCT

Nate Pet picture Nate Pet · Dec 19, 2011 · Viewed 138.1k times · Source

I am having a hard time doing the following:

select a.FirstName, a.LastName, v.District
from AddTbl a order by Firstname
inner join (select distinct LastName from
            ValTbl v  where a.LastName = v.LastName)  

I want to do a join on ValTbl but only for distinct values.

Answer

kol picture kol · Dec 19, 2011

Try this:

select distinct a.FirstName, a.LastName, v.District
from AddTbl a 
  inner join ValTbl v
  on a.LastName = v.LastName
order by a.FirstName;

Or this (it does the same, but the syntax is different):

select distinct a.FirstName, a.LastName, v.District
from AddTbl a, ValTbl v
where a.LastName = v.LastName
order by a.FirstName;