我需要一个SQL查询,每个ClientID按PlanDate
返回前2个计划。这一切都在一个表上,其中PlanID
是PrimaryID,ClientID
是foreignID。
这是我到目前为止 - >
SELECT *
FROM [dbo].[tblPlan]
WHERE [PlanID] IN (SELECT TOP (2) PlanID FROM [dbo].[tblPlan] ORDER BY [PlanDate] DESC)
这显然只返回2条记录,其中每ClientID
实际上最多需要2条记录。
答案 0 :(得分:5)
这可以使用ROW_NUMBER:
完成SELECT PlanId, ClientId, PlanDate FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY ClientId ORDER BY PlanDate DESC) rn, *
FROM [dbo].[tblPlan]
) AS T1
WHERE rn <=2
将所需的任何其他列添加到select中以获取这些列。
答案 1 :(得分:3)
编辑,2011年12月。更正了CROSS APPLY解决方案
尝试两者,看看什么是最好的
SELECT *
FROM
( -- distinct ClientID values
SELECT DISTINCT ClientID
FROM [dbo].[tblPlan]
) P1
CROSS APPLY
( -- top 2 per ClientID
SELECT TOP (2) P2.PlanID
FROM [dbo].[tblPlan] P2
WHERE P1.ClientID = P2.ClientID
ORDER BY P2.[PlanDate] DESC
) foo
或者
;WITH cTE AS (
SELECT
*,
ROW_NUMBER () OVER (PARTITION BY clientid ORDER BY [PlanDate] DESC) AS Ranking
FROM
[dbo].[tblPlan]
)
SELECT * FROM cTE WHERE Ranking <= 2