Question

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).

how would i do this? MS SQL2000 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

thanks

Was it helpful?

Solution

You need to use row_number() function, try something like this:

select
    link_to_client, call_ref 
from
    (
        select
            link_to_client, call_ref, 
            row_number() over (partition by link_to_client order by call_ref desc) n
        from 
            calls with (nolock) 
        where 
            link_to_client in ('G/1931') 
            and call_type = 'PM' 
    ) x
where
    n = 2 -- second result for every client

OTHER TIPS

Try this one -

SELECT 
      link_to_client
    , call_ref
FROM (
    SELECT 
          link_to_client
        , call_ref
        , rn = ROW_NUMBER() OVER (PARTITION BY link_to_client ORDER BY call_ref DESC)
    FROM dbo.calls WITH (NOLOCK)
    WHERE link_to_client = 'G/1931'
        AND call_type = 'PM'
) x
WHERE x.rn = 2

I think this will work in sqlserver 2000:

SELECT link_to_client, 
(
SELECT TOP 1 call_ref
FROM
(
    SELECT TOP 2 link_to_client
    FROM calls WITH (NOLOCK)
    WHERE link_to_client = a.link_to_client
        AND call_type = 'PM'
    ORDER BY call_ref DESC
) x
ORDER BY call_ref
) call_ref
FROM
(SELECT DISTINCT link_to_client
FROM calls WITH (NOLOCK)) a
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top