1

我有一个查询显示一位客户的第二个结果。我现在需要做的是在特定列表中显示每个客户的第二个结果(例如 20 个不同的客户 G/1931、G/1932、G/1933 等)。

我该怎么做?通过 SSMS 2005 的 Sql Server 2000

1 个客户的当前查询是

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
4

1 回答 1

2

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

于 2013-08-30T08:32:29.017 回答