sql-server – 获取每个id和status的前3个值

我有这样的数据,

ID        Time        Status
---       ----        ------
1          10           B
1          20           B
1          30           C
1          70           C
1         100           B
1         490           D

期望的结果应该是,

ID      Time       Status
1        490         D
1        100         B
1         70         C

这就是我应该获得ID和不同状态的前3个时间值.
为此,我试过: –

    ;WITH cte AS
(
   SELECT *,
         ROW_NUMBER() OVER (PARTITION BY id ORDER BY TIME DESC) AS rn
   FROM MyTable
)
SELECT  id,TIME,Status                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
FROM cte
where rn<=3

但它不符合我的要求iam gettng top 3重复staus值,我怎么能解决这个问题.帮助!

最佳答案 按状态划分:

WITH cte AS (
      SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY id, status
                                ORDER BY TIME DESC
                               ) AS rn
      FROM MyTable t
     )
SELECT id, TIME, Status 
FROM t
WHERE rn <= 3;
点赞