<span style="font-size:18px;">功能:查询订单表中每个顾客第一次下订单的订单号和时间;
(1)、临时表使用
USE AdventureWorks2008
GO
SELECT soh.CustomerID, MIN(soh.OrderDate) AS OrderDate
INTO #MinOrderDates
FROM Sales.SalesOrderHeader soh
GROUP BY soh.CustomerID;
SELECT soh.CustomerID, soh.SalesOrderID, soh.OrderDate
FROM Sales.SalesOrderHeader soh
JOIN #MinOrderDates t
ON soh.CustomerID = t.CustomerID
AND soh.OrderDate = t.OrderDate
GROUP BY soh.CustomerID
DROP TABLE #MinOrderDates
(2)、内联子查询
SELECT soh1.CustomerID, soh1.SalesOrderID, soh1.OrderDate
FROM Sales.SalesOrderHeader soh1
WHERE soh1.OrderDate = (SELECT Min(soh2.OrderDate)
FROM Sales.SalesOrderHeader soh2
WHERE soh2.CustomerID = soh1.customerID)
ORDER BY CustomerID;</span>
SqlServer_临时表查询和内联子查询的使用;
最新推荐文章于 2024-07-28 03:33:40 发布