提供在2008年7月1日之后已订购产品711和712的唯一的客户ID和帐号列表

时间:2018-06-22 23:18:31

标签: sql-server adventureworks

问题来自AdventureWorks2008R2

我尝试了此查询,但我只希望同时订购产品711和712的客户。例如,CustomerID 11441已订购产品ID 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 

我的输出截图

Screenshot of my output

1 个答案:

答案 0 :(得分:1)

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的操作将无法正常工作。