views:

34

answers:

3

Two simple tables:

T1

ContactId, Name, Department

T2

AddressId OwnerId Address Added

What I need to output is: ContactId, Name, Department, Address however I only want one record per cusomer, the oldest based on Added (datetime).

Is this possible?

+2  A: 

Yes it is possible.

You'll have to use a correlated subquery:

select contactid, name, department, address
from t1
inner join t2 x on t1.contactid = x.ownerid
where x.added = ( select max(t2.added) from t2 where t2.ownerid = x.ownerid )

Use an outer join when you want to return every contact:

select contactid, name, department, address
from t1
outer join t2 x on t1.contactid = x.ownerid
where x.added = ( select max(t2.added) from t2 where t2.ownerid = x.ownerid )
Frederik Gheysels
I'm not sure where it discrepancy is occuring but i have 69905 records in T1, 69804 records in T2 but the query is returning 69718 rows. I know there are some unmatched records in T2 (22 to be exact).I need every customer returning with null values when there is no address.
Anthony
That is because I specified an inner join, which makes sure that the resultset only contains a record when there is a matching record in t2.If you want to have every customer returned, then an outer join should be used.
Frederik Gheysels
A: 

You can do it as follows:

SELECT T1.contactId,T1.name,T2.department,T2.address FROM T1 INNER JOIN T2  ON T1.ContactId=T2.OwnerId INNER JOIN (SELECT OwnerId,MAX(Added) FROM T2 GROUP BY OwnerId) LatestAddress ON  T2.OwnerId=LatestAddress.OwnerId
Beatles1692
The LatestAddress 'table' doesn't contain the column AddressId.
Anthony
sorry! I edited my answer
Beatles1692
+1  A: 

Re-work of Frederik's solution, but should be faster if AddressID is your PK (clustered). Also use LEFT JOIN in case there are no addresses for the Contact. If one is sure to have one, then replace with INNER JOIN:

SELECT      t1.contactid, 
            t1.name, 
            t1.department, 
            t2.address
FROM        t1
LEFT JOIN   t2
        ON  t2.addressid = (SELECT  TOP 1 x.addressid 
                            FROM    t2 x 
                            WHERE   x.ownerid = t1.contactid
                            ORDER BY t2.added ASC)

Are you sure you want the oldest? Change ASC to DESC if you would like the newest.

van