我需要获取从未订购过订单的客户列表
我正在传递一个CustomerNumbers列表,抓住他们加入Orders然后我正在分组 - 我觉得我很接近但不确定如何获得没有Orders.Exported设置为1的客户。
这是我到目前为止所做的:
SELECT Customers.CustomerID,
Orders.Exported,
Count(Orders.OrderID) AS OrderCount
FROM Customers WITH (Nolock)
JOIN Orders ON Customers.ManufacturerID = Orders.ManufacturerID
AND Customers.CustomerNumber = Orders.CustomerNumber
WHERE Customers.CustomerNumber IN (
SELECT *
FROM dbo.Split(REPLACE(@CustomerNumbers,'\',''),','))
AND Customers.ManufacturerID=@ManufacturerID
AND Customers.Source = 'ipad'
GROUP BY Customers.CustomerID,
Orders.Exported
这几乎让我得到了我需要的东西,我的结果是:
CustomerID Exported OrderCount
375408 NULL 1
375408 1 5
375412 1 2
376892 NULL 1
所以在这个列表中我只想要376892,因为他们从未在
之前导出订单答案 0 :(得分:1)
您可以使用Having Min(IsNull(Orders.Exported,0))
Left Join
和删除分组 Orders.Exported
来过滤掉之前已导出订单的客户。
从逻辑上讲,您的点数将始终为0,因此您无需计算。
SELECT Customers.CustomerID, Min(IsNull(Orders.Exported,0)) Exported, Count(Orders.OrderID) As OrderCount
FROM Customers With (Nolock) LEFT JOIN Orders
ON Customers.ManufacturerID = Orders.ManufacturerID AND
Customers.CustomerNumber = Orders.CustomerNumber
WHERE Customers.CustomerNumber IN (
SELECT colName FROM dbo.Split(REPLACE(@CustomerNumbers,'\',''),',')) AND
Customers.ManufacturerID=@ManufacturerID AND Customers.Source = 'ipad'
GROUP BY Customers.CustomerID
HAVING Min(IsNull(Orders.Exported,0)) = 0
答案 1 :(得分:0)
WHERE Customers.CustomerNumber IN (SELECT * FROM dbo.Split(REPLACE(@CustomerNumbers,'\',''),','))
AND Customers.ManufacturerID=@ManufacturerID
AND Customers.Source = 'ipad'
AND Orders.Exported is NuLL
答案 2 :(得分:0)
WITH CustomersWithExportedOrders AS (
SELECT Customers.CustomerNumber
FROM Customers
INNER JOIN Orders
ON Customers.ManufacturerID = Orders.ManufacturerID
AND Customers.CustomerNumber = Orders.CustomerNumber
WHERE Orders.Exported IS NOT NULL
)
SELECT Customers.CustomerID
, Orders.Exported
, Count(Orders.OrderID) As OrderCount
FROM Customers
INNER JOIN Orders
ON Customers.ManufacturerID = Orders.ManufacturerID
AND Customers.CustomerNumber = Orders.CustomerNumber
WHERE Customers.CustomerNumber IN (SELECT *
FROM dbo.Split(REPLACE(@CustomerNumbers, '\', ''), ','))
AND Customers.ManufacturerID = @ManufacturerID
AND Customers.CustomerNumber NOT IN (SELECT CustomerNumber
FROM CustomersWithExportedOrders)
AND Customers.Source = 'ipad'
GROUP BY Customers.CustomerID
, Orders.Exported