简体   繁体   中英

How to calculate moving average DAYS of a date column

I have these columns and data Sample data:

CREATE TABLE Orders(customerid int, orderdate datetime, orderqty int);
INSERT into Orders(customerid, orderdate, orderqty) VALUES
    (1,'2020-11-25',100),(1,'2020-11-27',160),(2,'2020-12-05',3490),
    (1,'2020-11-29',293),(2,'2020-12-07',293),(1,'2020-12-01',382);

sqlfiddle: http://sqlfiddle.com/#!9/d90aaf/1/0

From this data, I want to find out the date difference in last 3 rows by each customer. an example output would be:

customerid, last 3 orders average days between orders,sum of orderqty for last 3 order
1, 2,835
2, 2,3783

I have tried datediff() but I can't achieve this result by that function.

Can't figure out better trick for latest 3 orders. This works, but probably with not good performance with large tables:

SELECT o3.customerid,DATEDIFF(Latest1,IFNULL(Latest3,Latest2))/IF(Latest3 IS NULL,1,2) AS avgDiff,SUM(oQ.orderqty) AS qty3orders FROM
(SELECT o2.*,MAX(ooo.orderdate) AS Latest3 FROM 
(SELECT o1.*,MAX(oo.orderdate) AS Latest2 FROM 
(SELECT customerid,MAX(orderdate) AS Latest1 FROM Orders GROUP BY customerid) o1 
JOIN Orders oo ON o1.customerid=oo.customerid AND oo.orderdate<o1.Latest1 GROUP BY o1.customerid) o2
LEFT JOIN Orders ooo ON o2.customerid=ooo.customerid AND ooo.orderdate<o2.Latest2 GROUP BY o2.customerid) o3
JOIN orders oQ ON o3.customerid=oQ.customerid AND oQ.orderdate>=COALESCE(o3.Latest3,o3.Latest2,o3.Latest1) GROUP BY o3.customerid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM