作者:手机用户2502858065 | 来源:互联网 | 2023-05-18 08:36
功能:查询订单表中每个顾客第一次下订单的订单号和时间;
(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;