我有一个查询显示一个客户的第二个结果。 我现在需要做的是显示特定列表中每个客户的第二个结果(例如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
感谢
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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