I think the most efficient way would be to exclude the minimum call_ref
for each link_to_client
, then take the minumum of that:
SELECT calls.link_to_client,
MAX(calls.Call_Ref) call_ref
FROM calls WITH (NOLOCK)
LEFT JOIN
( SELECT link_to_client, MAX(Call_Ref) call_ref
FROM calls WITH (NOLOCK)
WHERE calls.call_type = 'PM'
GROUP BY link_to_client
) MaxCalls
ON MaxCalls.link_to_client = calls.link_to_client
AND MaxCalls.Call_ref = calls.call_ref
WHERE calls.call_type = 'PM'
AND MaxCalls.link_to_Client IS NULL
GROUP BY calls.link_to_Client;
However if you wanted to extend this to get, for example the 5th for each customer then it would start to get messy. In which case I would use:
SELECT calls.link_to_client, calls.call_ref
FROM calls
WHERE 5 = ( SELECT COUNT(*)
FROM calls c2
WHERE c2.link_to_Client = calls.link_to_Client
AND c2.call_ref <= calls.call_ref
);
My final piece of advise would be to upgrade to a newer version of SQL-Server, where you can use ROW_NUMBER
!
Examples on SQL Fiddle
Thanks to Nenad Zivkovic for the fiddle