计算订单之间的平均天数 最近三条记录的sql

Calculate average days between orders The last three records tsql

我试图对每位客户取平均值,但您没有按客户分组。 我想从一个名为 table 的发票计算几个订单日期之间的平均天数。对于每个 BusinessPartnerID,订单之间的平均天数是多少我想要平均天数最后三个记录订单。 我得到了每个用户所有订单的平均值,但需要几天的最后三个记录订单 样本table如下

   ;WITH temp (avg,invoiceid,carname,carid,fullname,mobail)
AS
(
    SELECT AvgLag = AVG(Lag)  , Lagged.idinvoice,
     Lagged.carname ,
     Lagged.carid ,Lagged.fullname,Lagged.mobail
FROM 
(
 SELECT   
  
  (car2.Name) as carname ,
    (car2.id) as carid ,( busin.Name) as fullname, ( busin.Mobile) as mobail , INV.Id as idinvoice , Lag = CONVERT(int, DATEDIFF(DAY, LAG(Date,1) 
    OVER (PARTITION BY car2.Id ORDER BY Date ), Date))
     FROM  [dbo].[Invoice]    AS    INV
    JOIN  [dbo].[InvoiceItem] AS INITEM  on INV.Id=INITEM.Invoiceid
    JOIN [dbo].[BusinessPartner]  as busin on busin.Id=INV.BuyerId and Type=5
    JOIN [dbo].[Product] as pt on pt.Id=INITEM.ProductId and  INITEM.ProductId is not null and  pt.ProductTypeId=3  
    JOIN [dbo].[Car] as car2 on car2.id=INv.BusinessPartnerCarId 
    
    
) AS Lagged 
 GROUP BY
  Lagged.carname,
 Lagged.carid,Lagged.fullname,Lagged.mobail, Lagged.idinvoice

 -- order by Lagged.fullname
  
  )
 SELECT  *  FROM temp  where avg is not null   order by avg  

我真的不明白你的查询与你的问题有什么关系。从一个名为 invoice 的 table 开始,它包含 businesspartneriddate 列,下面是您如何计算每家企业最后 3 张发票之间的天差的平均值合作伙伴:

select businesspartnerid, 
    avg(1.0 * datediff(
        day, 
        lag(date) over(partition by businesspartnerid order by date),
        date
    ) avg_diff_day
from (
    select i.*,
        row_number() over(partiton by businesspartnerid order by date desc) rn
    from invoice i
) i
where rn <= 3
group by businesspartnerid

请注意,3 行仅提供 2 个间隔,将取平均值。