I would like to calculate the average days between several order dates from a table called Orders. For each CustomerID, what is the average days between orders. The sample table is as below (img):
CREATE TABLE #Orders(CustomerID int, OrderDate datetime);
INSERT #Orders(CustomerID, OrderDate) VALUES
(100,'20170114'),(100,'20170123'),(100,'20170129'),
(101,'20170202'),(101,'20170212');
I tried this query:
SELECT CustomerID, AVG(OrderDate - PriorDate)
FROM (SELECT CustomerID, OrderDate
, LAG(OrderDate) OVER (PARTITION BY CustomerID ORDER BY OrderDate) as PriorDate
FROM #Orders where CustomerID = 100)
However, this yields:
Msg 102, Level 15, State 1
Incorrect syntax near ')'.
Best Answer
Several issues:
OrderDate-PriorDate
) is not a good idea (try that with date or datetime2) - useDATEDIFF
.SELECT 5/2;
. You need to convert at least one input to a decimal, either implicitly (*1.0
) or explicitly (CONVERT(), TRY_CONVERT(), CAST(), etc.
). Explicit allows you to control decimal places in some cases.LAG()
was not complete - while the default is 1, I think it is good to be explicit that you want the previous row.SELECT ... FROM (<subquery>)
, that subquery needs to be named, so you need to use something likeSELECT ... FROM (<subquery>) AS x;
for example.Try the following:
Results:
Of course, if you want the average for all customers, just leave out the
WHERE
clause. But if you really only ever want a single customer, you don't really need the customer in the output, so you can adjust the query a little bit to get rid of theGROUP BY
(let's parameterize the customer ID while we're at it):