The problem is that we need to get the total number of lines before and after a given line (identified by, say, the primary key).
I tried following in T-SQL (MSSQL 2008). This gives the correct result, but I do not know if this is the best for this.
;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
How can we improve it in T-SQL and how can we achieve it in other dialects of SQL and the server (for example, Oracle, MySQL, sqlite, FireBird, etc.).
source share