我需要找到客户第二笔订单到第三笔订单之间的平均时间(天)
我知道我需要使用timestampdiff
,但是对于如何选择第二个和第三个日期并需要某种嵌套非常不知所措。
SELECT CustomerID,
OrderDate,
diff,
avg(timestampdiff(day, start_date, end_date)) AS average_days
FROM () o3
WHERE date3, date2
ORDER BY CustomerID, OrderDate;
表格
答案 0 :(得分:1)
要获得所需的结果,首先需要根据数据PARTITION BY CustmerId计算ROW_NUMBER。然后仅使用RowNumber IN(2,3)保留行,然后在两天之间获取DateDiff。以下查询将帮助您获得所需的结果-
SELECT CustomerID,datediff(MAX(OrderDate),MIN(OrderDate))
FROM
(
SELECT *,
@row_num :=IF(@prev_value = concat_ws('',CsutomerID),@row_num+1,1)AS RowNumber
, @prev_value := concat_ws('',CsutomerID)
FROM your_table A
ORDER BY CustomerID,OrderDate
)B
WHERE B.RowNumber IN (2,3)
GROUP BY CustomerID;