我正致力于在SQL Server中的客户级别上平均两天之间的平均天数。
SELECT
CUSTOMER,
VISIT_ID,
DAYIN_DATE,
DAYOUT_DATE,
RANK () OVER (PARTITION BY CUSTOMER ORDER BY VISIT_ID DESC) AS RANKING,
LAG(DAYOUT_DATE, 1)
OVER (PARTITION BY CUSTOMER ORDER BY VISIT_ID DESC) AS DATEOUT_DT,
LEAD(DAYIN_DATE, 1)
OVER (PARTITION BY CUSTOMER ORDER BY VISIT_ID DESC) AS DATEIN_DT,
(DATEIN_DT - DATEOUT_DT) AS LATENCY
FROM VISIT_TABLE
GROUP BY 1,2,3,4;
此代码获取客户并访问(唯一ID),然后按DAYIN_DATE / DAYOUT_DATE对其进行排名。我已经编写了一个Lag and Lead函数来帮助计算延迟,但是当平均时它不会在客户级别上进行平均。
我错过了什么?
结果:
CUSTOMER VISIT_ID CHECKIN_DATE CHECKOUT_DATE RANKING CHECKIN_DT CHECKOUT_DT LATENCY 999999999 1111111111 4/27/2015 4/28/2015 1 8/20/2014 (null) (null) 999999999 2222222222 8/20/2014 8/21/2014 2 8/19/2014 4/28/2015 252 999999999 3333333333 8/19/2014 8/20/2014 3 8/18/2014 8/21/2014 3 999999999 4444444444 8/18/2014 8/19/2014 4 8/17/2014 8/20/2014 3 999999999 5555555555 8/17/2014 8/18/2014 5 7/4/2014 8/19/2014 46 999999999 6666666666 7/4/2014 7/6/2014 6 4/15/2014 8/18/2014 125
期望的结果:
CUSTOMER_ID AVGLATENCY_PER_CUST 999999999 17 888888888 12
答案 0 :(得分:1)
您没有指定表的设置方式,因此根据您的尝试,我认为该表具有CUSTOMER,VISIT_ID,DATEIN_DT,DATEOUT_DT。
如果DATEIN_DT和DATEOUT_DT是日期,则可以使用average和datediff函数,然后按客户端分组。
示例:
SELECT
CLIENT,
AVG(DATEDIFF(dd,DATEIN_DT,DATEOUT_DT)) AverageVisitTime
FROM VISIT_TABLE
GROUP BY CLIENT