SQL查询,按外键按日期排序前2

时间:2010-02-02 20:48:37

标签: sql-server-2005 greatest-n-per-group sql

我需要一个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条记录。

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