最后X个订单的平均值

时间:2016-10-10 13:33:57

标签: sql sql-server

我需要找到每位客户最后X个订单的平均金额。我的数据结构如下:

  • 客户ID
  • 总金额
  • 日期

我尝试按客户ID进行分区,然后按日期排序,但我无法找到TOP X的平均值。

3 个答案:

答案 0 :(得分:1)

另一个选项是cte和Row_Number()。以下将为您提供客户的平均订单。

Declare @YourTable table (CustID int,OrderDate Date,OrderAmount int)
Insert Into @YourTable values
(1,'2016-01-18',2500),
(1,'2016-02-13',5000),
(1,'2016-03-31',3000),
(2,'2016-03-18',1800),
(2,'2016-04-13',2200),
(2,'2016-05-31',2500)

;with cteBase as (
    Select *
          ,RowNr=Row_Number() over (Partition By CustID Order By OrderDate Desc) 
    From @YourTable
)
Select CustID
      ,AvgOrder = avg(OrderAmount)
 From cteBase
 Where RowNr<=2
 Group By CustID

返回

CustID  AvgOrder
1       4000
2       2350

答案 1 :(得分:0)

使用ROW_NUMBER窗口功能

select [Customer ID],Avg([Total Amount]) as avg_amt
(
select row_number()over(partition by [Customer ID] order by [Date] desc) rn, *
from yourtable
) A
Where Rn <= 5 --change it based on requirement 
Group by [Customer ID]

看起来当前表是事务表,因此您可能有一个名为Customer的单独表,其中[Customer ID]是唯一的,那么您也可以使用此方法

SELECT c.[Customer ID],
       Avg([Total Amount])
FROM   customers c
       CROSS apply (SELECT TOP 5 [Total Amount]
                    FROM   yourtable y
                    WHERE  c.[Customer ID] = y.[Customer ID]
                    ORDER  BY [Date] DESC) cs
GROUP  BY [Customer ID] 

上述查询可以使用OUTER APPLY进行更改,以获取所有customers的列表,即使他没有使用avg Total Amount零进行任何交易。

答案 2 :(得分:0)

一种方法使用row_number()

select customerid, avg(totalamount)
from (select t.*,
             row_number() over (partition by customerid order by date desc) as seqnum
      from t
     ) t
where seqnum <= x;