问题来自AdventureWorks2008R2
我尝试了这个查询,但我只想要订购产品711和712的客户。例如,CustomerID 11441订购了productid 711和712,因此只显示11441
Select DISTINCT(oh.CustomerID), oh.AccountNumber, CAST(oh.OrderDate as DATE) OrderDates, od.ProductID
From Sales.SalesOrderHeader oh
Inner Join Sales.SalesOrderDetail od
ON od.SalesOrderID = oh.SalesOrderID
WHERE od.ProductID BETWEEN 711 AND 712
AND CAST(oh.OrderDate as DATE) > '2008-07-01'
ORDER BY oh.CustomerID
SELECT
oh.CustomerID, oh.AccountNumber,
CAST(oh.OrderDate as DATE) OrderDates, /* doesn't really make sense as a plural */
od.ProductID
FROM Sales.SalesOrderHeader oh
WHERE CAST(oh.OrderDate as DATE) > '2008-07-01'
AND (
SELECT COUNT(DISTINCT ProductID)
FROM SalesOrderDetail od
WHERE od.SalesOrderID = oh.SalesOrderID
AND od.ProductID IN (711, 712)
) = 2
ORDER BY oh.CustomerID;
这是使用相关子查询的一种方法。顺便说一句,你在原始查询中尝试用DISTINCT
做的事情是行不通的。