我需要使用TSQL来计算客户交易之间的天数的标准差。该表有两列,CustomerId和TranDate。每位客户至少有3个独特的交易日期。例如,客户abc的交易日期可能是1/1 / 13,1 / 4 / 13,1 / 10/13和1/20/13。交易之间的天数则为3,6和10 - 因此代码应返回客户abc的标准差2.867。
如何按照客户分组的方式对任何数量的交易进行编码?
答案 0 :(得分:1)
select id, stdev(DATEDIFF ( dd , '1/1/1900' , enddate ))
from table
group by id
with dateOrder as
(SELECT [fieldID], [value],
row_number() over (partition by [fieldID] order by [value]) as row
FROM [docSVdate])
select do1.fieldID, stdev(datediff(dd, do1.value, do2.value))
from dateOrder as do1
join dateOrder as do2
on do1.fieldID = do2.fieldID
and do2.row = do1.row + 1
group by do1.fieldID