这篇文章主要为大家详细介绍了SQL Server 获得用户最新或前n条订单的几种SQL语句用法,具有一定的参考价值,可以用来参考一下。
感兴趣的小伙伴,下面一起跟随四海网的小编两巴掌来看看吧!
实现以上要求,我们可以用以下几种方式,但是效率却相差很远。代码如下:
SELECT EmployeeID,OrderID FROM Orders AS O1
WHERE OrderID = (
SELECT TOP(1)OrderID FROM Orders AS O2
WHERE O1.EmployeeID = O2.EmployeeID
ORDER BY OrderDate DESC ,OrderID DESC
)
代码如下:
SELECT O.EmployeeID,O.OrderID FROM (
SELECT EmployeeID,(SELECT TOP(1)OrderID FROM Orders AS O2 WHERE E.EmployeeID = O2.EmployeeID ORDER BY OrderDate DESC,OrderID DESC) AS OrderID
FROM Employees AS E
) AS EO
INNER JOIN Orders AS O
ON EO.OrderID = O.OrderID
代码如下:
SELECT E.EmployeeID,O.OrderID FROM Employees AS E
CROSS APPLY (
SELECT TOP(1)* FROM Orders AS O1 WHERE E.EmployeeID = O1.EmployeeID ORDER BY O1.OrderDate DESC,O1.OrderID DESC
) AS O
代码如下:
SELECT O1.EmployeeID,O1.OrderID
FROM Orders O1 JOIN (
SELECT ROW_NUMBER() OVER(PARTITION BY EmployeeID ORDER BY OrderDate DESC,OrderID DESC) AS RowNumber,*
FROM Orders AS OT
) AS O2
ON O1.OrderID = O2.OrderID
WHERE O2.RowNumber = 1
本文来自:http://www.q1010.com/179/8081-0.html
注:关于SQL Server 获得用户最新或前n条订单的几种SQL语句用法的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。
关键词:SQL SERVER
四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。