如何在TSQL中编写带有row_number的WHERE子句?

问题描述 投票:0回答:1
WITH CTE AS (
SELECT *, ROW_NUMBER () OVER (PARTITION BY id ORDER BY opened_at) RN
FROM table)

SELECT column1, column2
FROM CTE
WHERE RN = 2

--如果没有 RN=2,如何返回 RN = 1?如果我编写类似 WHERE RN = IIF (RN = 2,2,1) 的代码,对于具有 1 和 2 的行,它将返回 RN = 1 和 RN =2。我只需要 RN =2 或 RN =1,如果 RN =2 则不适用。

如有任何建议,我们将不胜感激。

谢谢!

sql t-sql where-clause ssms row-number
1个回答
0
投票

您可以通过获取每个 id 的最大 rn 来做到这一点,其中 rn 应小于 2 :

WITH CTE AS (
SELECT *, ROW_NUMBER () OVER (PARTITION BY id ORDER BY opened_at) RN
FROM mytable
)
SELECT c.*
FROM CTE c
INNER JOIN (
  SELECT id, max(rn) as max_rn
  FROM CTE
  where rn <= 2
  GROUP BY id
) as s on s.id = c.id and s.max_rn = c.rn
© www.soinside.com 2019 - 2024. All rights reserved.