This may be a case for cross-apply
select T1.ID, T1.Name, T1.Address1, T2.item, T2.Visit_date from
Table1 T1 cross apply (select top 1 * from Table2 where ID = Table1.ID
order by Visit_date desc) T2
Question
I have 2 tables, for example:
Table1
ID,Name,Address1
Table2
Visit_date,item,id
Table 2 has lots of visits logged, and the id of the address.
I want to write a query that selects all Names and Addresses and their LAST visit date and item.
SELECT *
FROM (SELECT ID, NAME, ADDRESS FROM table1) as temp
RIGHT JOIN table2 ON table1.ID = temp.ID;
Is as far as I have gotten so far.
Solution 2
This may be a case for cross-apply
select T1.ID, T1.Name, T1.Address1, T2.item, T2.Visit_date from
Table1 T1 cross apply (select top 1 * from Table2 where ID = Table1.ID
order by Visit_date desc) T2
OTHER TIPS
You could use ROW_NUMBER
in a CTE.
;WITH cte AS (
SELECT t1.name, t1.address1, t2.Visit_date, t2.item,
ROW_NUMBER() OVER (PARTITION BY t2.id ORDER BY t2.visit_date DESC) AS rn
FROM table2 t2
INNER JOIN table1 t1
ON t1.id = t2.id
)
SELECT name, address1, visit_date, item
FROM cte
WHERE rn = 1