Search code examples
sqlsql-serversql-server-2000

Show second result for multiple records


I've got a query that displays the second result for one customer. what i now need to do is show the second result for each customer in a particular list (for example 20 different customers G/1931, G/1932, G/1933 etc etc).

how would i do this? Sql Server 2000 via SSMS 2005

current query for 1 customer is

SELECT TOP 1 link_to_client, call_ref
FROM
(
    SELECT TOP 2 link_to_client, call_ref
    FROM calls WITH (NOLOCK)
    WHERE link_to_client IN ('G/1931')
        AND call_type = 'PM'
    ORDER BY call_ref DESC
) x
ORDER BY call_ref

Solution

  • 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