我需要一个查询,它可以在10天内为客户提供相同生产订单的结果。由于生产管理,制造商不喜欢在短时间内多次订购相同产品的客户(例如10天对我而言)
以下是示例订单表代码。
DECLARE @Orders TABLE(Customer VARCHAR(50), Product VARCHAR(50), OrderDate DATE)
INSERT INTO @Orders VALUES
('A Company','w102', '2016-10-10'),('A Company','w102', '2016-10-12'),('A Company','w102', '2016-10-24'),
('B Company','w302', '2016-11-11'),('B Company','w302', '2016-11-15'),('B Company','w302', '2016-11-17'),
('C Company','w404', '2016-11-17'),('C Company','w404', '2016-11-24'),('C Company','w405', '2016-11-24')
select * from @Orders ORDER BY Customer, OrderDate
那么如何才能在10天内获得客户订单列表相同的内容?
答案 0 :(得分:1)
您可以在原始订单的10天内使用EXISTS
检查与同一客户和产品的其他订单:
SELECT *
FROM @Orders AS o
WHERE EXISTS
( SELECT 1
FROM @Orders AS o2
WHERE o2.Customer = o.Customer
AND o2.Product = o.Product
AND o2.OrderDate > o.OrderDate
AND o2.OrderDate <= DATEADD(DAY, 10, o.OrderDate)
);
给出了:
Customer Product OrderDate
---------------------------------------
A Company w102 2016-10-10
B Company w302 2016-11-11
B Company w302 2016-11-15
C Company w404 2016-11-17
这只会返回两个订单中第一个订单的详细信息,如果您需要下一个订单的详细信息(例如日期),那么您可以使用CROSS APPLY
:
SELECT o.Customer,
o.Product,
FirstOrderDate = o.OrderDate,
NextOrderDate = o2.OrderDate
FROM @Orders AS o
CROSS APPLY
( SELECT TOP 1 o2.OrderDate
FROM @Orders AS o2
WHERE o2.Customer = o.Customer
AND o2.Product = o.Product
AND o2.OrderDate > o.OrderDate
AND o2.OrderDate <= DATEADD(DAY, 10, o.OrderDate)
ORDER BY o2.OrderDate
) AS o2;
给出了:
Customer Product FirstOrderDate NextOrderDate
------------------------------------------------
A Company w102 2016-10-10 2016-10-12
B Company w302 2016-11-11 2016-11-15
B Company w302 2016-11-15 2016-11-17
C Company w404 2016-11-17 2016-11-24
仅在SQL Server 2012及更高版本中可用的第三个版本将使用LEAD()
或LAG()
:
SELECT o.Customer,
o.Product,
o.FirstOrderDate,
o.NextOrderDate
FROM ( SELECT o.Customer,
o.Product,
FirstOrderDate = o.OrderDate,
NextOrderDate = LEAD(o2.OrderDate) OVER(PARTITION BY Customer, Product ORDER BY o.OrderDate)
FROM @Orders AS o
WHERE o2.Customer = o.Customer
) AS o
WHERE o.NextOrderDate > o.FirstOrderDate
AND o.NextOrderDate <= DATEADD(DAY, 10, o.FirstOrderDate);