我有一个显示一个客户的第二个结果的查询。我现在需要做的是在特定列表中显示每个客户的第二个结果(例如20个不同的客户G / 1931,G / 1932,G / 1933等)。
我该怎么做? Sql Server 2000通过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 :(得分:2)
我认为最有效的方法是排除每个call_ref
的最低link_to_client
,然后取最小值:
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;
但是如果你想扩展这个以获得,例如每个客户的第5个,那么它将开始变得混乱。在这种情况下,我会使用:
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
);
我的最后建议是升级到更新版本的SQL-Server,您可以使用ROW_NUMBER
!
感谢小提琴的Nenad Zivkovic