概述:
我有限定半径(20英里)的商店。我有客户。如果客户距离商店不到20英里,则客户被分配到该商店。如果一个客户距离超过1个商店不到20英里,则客户被分配到客户花费最多的商店。
以上是实施和工作正常。但现在我有了新的要求,我需要帮助。商店现在限制了最大分配客户数量。 所以我的问题是,当一个客户可以被分配到两个商店,并且由于大多数钱花费而假设客户被分配到该商店,但是该商店已经达到了最大分配客户数量。在这种情况下,必须将客户分配到shop2
到目前为止的查询:
-- assigned all customers to all shops
INSERT INTO #assignment
SELECT cd.ap_business_id ,
cb.customer_id ,
dist.distance
FROM shops cd
CROSS JOIN customer cb
JOIN ZipDistance dist ON dist.zip1 = cd.business_zip
AND cb.zip = dist.zip2
-- If customer is assigned to more than one shop, keep the assignment to the shop that is closest to the customer
-- or to the shop where the customer spends most money. Remove other assignments.
;
WITH CTE
AS ( SELECT a.ap_business_id ,
a.customer_id ,
a.vehicle_id ,
ROUND(a.distance, 1) AS distance ,
db$.max_dealer_net_sales AS total1 ,
b$.max_dealer_net_sales AS total2 ,
ROW_NUMBER() OVER ( PARTITION BY a.customer_id ORDER BY ROUND(a.distance,
1) ASC, ISNULL(c$.max_shop_net_sales,
0) DESC, a.customer_id ) AS RN
FROM #assignment a -- total $ that given Business spend for collision parts
LEFT JOIN ( SELECT ap_business_id ,
SUM(amount) AS max_customer_net_sales
FROM customer_payments iq
WHERE iq.close_date > DATEADD(YEAR, -1,
GETDATE())
GROUP BY iq.ap_business_id
) c$ ON c$.ap_business_id = a.ap_business_id
WHERE a.customer_id IN ( SELECT vehicle_id
FROM #assignment aa
GROUP BY aa.customer_id
HAVING COUNT(*) > 1 )
)
DELETE #assignment
FROM #assignment a
JOIN CTE c ON a.ap_business_id = c.ap_business_id
AND a.customer_id = c.customer_id
AND c.RN > 1