我感兴趣的是从数据库表中选择第n行的一些(理想的)数据库不可知的方法。看看如何使用以下数据库的本机功能来实现这一点也很有趣:
SQL Server
MySQL
PostgreSQL
SQLite
甲骨文
我目前正在SQL Server 2005中做以下事情,但我有兴趣看到其他更不可知论的方法:
WITH Ordered AS (
SELECT ROW_NUMBER() OVER (ORDER BY OrderID) AS RowNumber, OrderID, OrderDate
FROM Orders)
SELECT *
FROM Ordered
WHERE RowNumber = 1000000
以上SQL: Firoz Ansari的Weblog的功劳
更新:参见Troels Arvin关于SQL标准的回答。Troels,你有我们可以引用的链接吗?
如果你想查看本机功能:
MySQL, PostgreSQL, SQLite和Oracle(基本上SQL Server似乎没有这个函数),你实际上可以使用NTH_VALUE窗口函数。
Oracle来源:Oracle函数:NTH_VALUE
实际上,我已经在我们的Oracle DB中对此进行了一些实验,以比较第一行(排序后)和第二行(同样是排序后)。
代码看起来像这样(如果你不想去链接):
SELECT DISTINCT dept_id
, NTH_VALUE(salary,2) OVER (PARTITION BY dept_id ORDER BY salary DESC
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
AS "SECOND HIGHEST"
, NTH_VALUE(salary,3) OVER (PARTITION BY dept_id ORDER BY salary DESC
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
AS "THIRD HIGHEST"
FROM employees
WHERE dept_id in (10,20)
ORDER
BY dept_id;
我发现它很有趣,我希望他们能让我用它。
我在这里有点晚了,但我已经在不需要窗口或使用的情况下做到了这一点
WHERE x IN (...)
SELECT TOP 1
--select the value needed from t1
[col2]
FROM
(
SELECT TOP 2 --the Nth row, alter this to taste
UE2.[col1],
UE2.[col2],
UE2.[date],
UE2.[time],
UE2.[UID]
FROM
[table1] AS UE2
WHERE
UE2.[col1] = ID --this is a subquery
AND
UE2.[col2] IS NOT NULL
ORDER BY
UE2.[date] DESC, UE2.[time] DESC --sorting by date and time newest first
) AS t1
ORDER BY t1.[date] ASC, t1.[time] ASC --this reverses the order of the sort in t1
它似乎工作得相当快,尽管公平地说,我只有大约500行数据
这在MSSQL中有效