从表中获取最新的2条记录

时间:2015-09-04 08:42:02

标签: sql sql-server sql-server-2008

我有一个像这样的SQL Server表

ProdID              Code
--------           ------
 1001                A
 2001                B
 1001                C
 3001                D
 3001                E
 1001                F
 1001                Z
 2001                G
 2001                H
 3001                I
 4001                J

我期待输出为

 ProdID              Code
 --------           ------
  1001                Z
  1001                F
  2001                H
  2001                G
  3001                I
  3001                E

仅显示最新的2个数据。如果任何id少于2个数据,我不想显示它(如ProdID 4001)。

2 个答案:

答案 0 :(得分:2)

试试这个

;With cte As
(Select ProdID, Code, Row_Number() Over(Partition By ProdID Order By Code Desc) As rn,
   Count(*) Over(Partition By ProdID) As NbrRows
From mytable)
Select ProdID, Code
From cte
Where rn <= 2 And NbrRows > 1
Order By ProdID, Code desc;

<强> sql fiddle demo

答案 1 :(得分:1)

使用ROW_NUMBERCOUNT

SQL Fiddle

;WITH cte AS(
    SELECT *,
        rn = ROW_NUMBER() OVER(PARTITION BY ProdID ORDER BY Code DESC),
        cnt = COUNT(*) OVER(PARTITION BY ProdID)
    FROM tbl
)
SELECT
    ProdID, Code
FROM cte
WHERE
    rn <= 2
    AND cnt >= 2