2

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

我该怎么做?MS SQL2000 通过 SSMS 2005

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

3 回答 3

3

您需要使用row_number()函数,尝试这样的事情:

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
于 2013-08-29T09:34:34.673 回答
1

我认为这将在 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
于 2013-08-30T09:40:37.627 回答
1

试试这个——

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
于 2013-08-29T09:35:26.303 回答