select b.branch_name, d.cashbook_ref from cashup_banking_det d Inner Join ( Select x.guid, x.date_time, x.terminal_id From ( Select Row_Number() Over (Partition By terminal_id Order By h.date_time Desc) As rownum , h.guid, h.date_time, h.terminal_id From [dbo].[cashup_banking_hdr] h where h.date_time > getdate()-14 ) x Where x.rownum = 1) y on y.guid = d.guid_hdr inner join terminal t on t.terminal_id = y.terminal_id inner join vw_branchwarehouse b on b.branch_no = t.branch_no order by branch_name