问题是我们要获得给定行之前和之后的行总数(由主键标识)。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的,火鸟等)
由于'[quote]字符的非标准用法,该语句将永远不会与任何其他DBMS一起运行。如果您避免需要引用或使用标准'“字符的列名,上述语句将在Oracle,PostgreSQL,DB2(以及即将推出的Firebird 3.0,因为它也支持窗口函数)运行 – 2011-03-01 20:30:12
是@a_horse_with_no_name(它将会更好,如果你得到一个名字)这只是为了t-sql – TheVillageIdiot 2011-03-02 03:45:39