一尘不染

SQL:给定行之前和之后的行数

sql

问题是我们要获取给定行之前和之后的行总数(由主键标识)。

我曾在T-SQL(MSSQL 2008)中尝试过以下方法。它给出了正确的结果,但是我不知道这是否是最好的方法。

;WITH cte_before AS 
(
    SELECT ROW_NUMBER() OVER ( Order By CustomerId ) [Row Number], customerid, 
           firstName 
    FROM SalesLT.Customer
 ),
cte_nums AS 
(
    SELECT ROW_NUMBER() OVER ( Order By CustomerId ) [Row Number1] 
    FROM SalesLT.Customer
)
SELECT [Row Number]-1 [before], MAX([Row Number1]) - [Row Number]
       , CustomerID, FirstName 
FROM cte_nums, cte_before
GROUP BY [Row Number], CustomerID, FirstName
HAVING CustomerID = 55

我们如何才能在T-SQL中改进它,以及如何在其他SQL方言和服务器(例如Oracle,MySQL,sqlite,FireBird等)中完成它?


阅读 125

收藏
2021-05-30

共1个答案

一尘不染

我认为这适用于任何方言:

select 
   (select count(*) from SalesLT.Customer where customerid < 55) as rows_before,
   (select count(*) from SalesLT.Customer where customerid > 55) as rows_after,
   CustomerID, FirstName
from SalesLT.Customer
where CustomerID = 55
2021-05-30