计算自上次OrderDate TSQL查询以来的天数

时间:2018-09-25 00:39:45

标签: sql-server tsql subquery correlated-subquery

我的任务是编写一个查询,以返回客户ID为90的客户的所有订单,以及订单总数和自客户上次订单以来的天数。

我要使用相关子查询来计算自上次订单以来的天数。

我正在使用WideWorldImporters示例数据库中的表Sales.Orders和Sales.OrderLines。

我必须具有列 OrderID,OrderDate,OrderTotal和DaysSincePreviousOrder 。后者是自客户上一次下单以来的日子。

我尝试解决方案的过程如下:

SELECT 
O.OrderID,
O.OrderDate,
ISNULL(SUM(OL.UnitPrice * OL.Quantity), 0.00) AS OrderTotal,
DATEDIFF(DAY, 
(
    SELECT MAX(OrderDate)
    WHERE OrderDate < O.OrderDate 
), O.OrderDate) AS DaysSincePreviousOrder       

FROM Sales.Orders O
    INNER JOIN Sales.OrderLines OL ON OL.OrderID = O.OrderID
            AND O.CustomerID = 90
GROUP BY O.OrderID, O.OrderDate, O.CustomerID
ORDER BY O.OrderID;

我不确定如何在相关子查询中获取客户先前订单的日期。

我的前两个结果应如下所示:

**OrderID**---  **OrderDate**   ------**OrderTotal**    -----**DaysSincePreviousOrder**  
1455    -------2013-01-29   -----365.00    --------- NULL  
1890    -------2013-02-06   -----915.00     ----------8

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

您可以使用LAG () OVER ()获取上一个订购日期。然后计算日期差

SELECT O.OrderDate,
       DATEDIFF(DAY, 
                LAG(O.OrderDate) OVER (PARTITION BY CustomerID Order by O.OrderDate),
                O.OrderDate) AS DaysSincePreviousOrder

答案 1 :(得分:1)

也许这会有所帮助。

create table MyOrder ( OrderID int,
                       CustomerID int,
                       OrderDate  date )

insert into MyOrder ( OrderID, CustomerID, OrderDate ) values
( 1, 9999, '2018-05-01T00:00:00.000' ),
( 2, 9999, '2018-05-10T00:00:00.000' ),
( 3, 9999, '2018-06-10T00:00:00.000' ),
( 4, 7777, '2018-07-01T00:00:00.000' ),
( 5, 7777, '2018-07-15T00:00:00.000' ),
( 6, 3333, '2018-09-09T00:00:00.000' )

select OrderID, 
       CustomerID, 
       OrderDate,

       ( select max(OrderDate) 
         from MyOrder 
         where     CustomerID = O.CustomerID 
               and OrderDate < O.OrderDate ) 
         as PreviousOrderDate

from MyOrder O
order by CustomerID, OrderDate

答案 2 :(得分:0)

大卫·杜波依斯(David Dubois)的答案几乎是正确的,但是并不能说明当天的订单。

where CustomerID = O.CustomerID and OrderID < O.OrderID

代替

where CustomerID = O.CustomerID and OrderDate < O.OrderDate

将解决该问题。