WITH recorddates
AS
(
SELECT PKEY, REFNo, DATE,
ROW_NUMBER() OVER (PARTITION BY RefNO
ORDER BY DATE DESC) rn
FROM table2
)
SELECT a.PKEY,
datediff(day,a.DATE,b.date)
FROM table1 a
INNER JOIN recorddates b
ON a.PKey = b.RefNo
WHERE b.rn = 1