访问 - 如何计算订单之间的平均天数(无光标)

时间:2016-08-16 20:31:20

标签: date ms-access cursor average

我想在访问中创建一个返回订单之间平均天数的查询。 表结构是: 表名:

 Orders

表格列

idOrder (integer)
 idClient (integer)
 OrderDate (date in format dd/mm/yyyy)
 OrderAmount (money)

对表的简单查询将返回:

1 1131 01/01/2015 $235
2 1145 02/01/2015 $11
3 1131 03/01/2015 $256
4 1131 04/01/2015 $300
5 1146 05/01/2015 $25
6 1145 10/01/2015 $15
7 1145 20/01/2015 $4
8 1131 21/01/2015 $45

在这个例子中,

client 1131 has orders on the days: 01/01/2015; 03/01/2015; 04/01/2015; 21/01/2015
client 1145 has orders on the days: 02/01/2015; 10/01/2015; 20/01/2015
client 1146 has orders on days: 05/01/2015

我想创建一个查询,为每个客户返回订单之间的平均天数:

1131 5
1145 6
1146 null

如果它是sql server,我会使用游标,但在Access中,我不知道该怎么做。

任何帮助?

2 个答案:

答案 0 :(得分:2)

您在SQL Server中不需要游标。 话虽如此,请尝试以下查询。 如果客户下了一个订单,逻辑上结果应为0(零),而不是空。 Null应该反映任何没有下订单的客户。

SELECT Orders.idClient, (Max(Orders.OrderDate)-Min(Orders.OrderDate))/Count(*) AS [Days between orders]
FROM Orders
GROUP BY Orders.idClient

答案 1 :(得分:1)

创建一个这样的查询:

Select
    idClient,
    Avg(DaysPast) As AverageOrderDays
From    
    (Select 
        idClient, 
        DateDiff("d",
                (Select Max(T.[Purchase Week]) 
                From Orders As T 
                Where T.idClient=Orders.idClient 
                And T.[Purchase Week] < Orders.[Purchase Week]),
            [Purchase Week]) AS DaysPast
    From 
        Orders) As OrderDays
Group By
    idClient