Domanda

I need to use TSQL to calculate the standard deviation of the number of days between transactions by customer. The table has two columns, CustomerId and TranDate. Each customer has at least 3 unique transaction dates. For example, customer abc may have transaction dates of 1/1/13, 1/4/13, 1/10/13, and 1/20/13. The number of days between transactions would then be 3, 6, and 10 - so the code should return a standard deviation of 2.867 for customer abc.

How can this be coded in such a way as to group by customer, for any number of transactions?

È stato utile?

Soluzione

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top