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

问题描述 投票:1回答:1

问题来自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 

Screenshot of my output

Screenshot of my output

sql-server adventureworks
1个回答
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做的事情是行不通的。

© www.soinside.com 2019 - 2024. All rights reserved.