The SQL below performs the requested operation. It averages days between the dates of the last three purchases, called here A,B,C. Being A the oldest of the three and C the most recent of the three.
select
client_report_id,
datediff(dd,A,B) DIFF_A_B,
datediff(dd,B,C) DIFF_B_C,
(datediff(dd,A,B) + datediff(dd,B,C))/2 media,
A,
B,
C
from
(
SELECT
client_report_id,
max(case when rownum = 3 then received_date end) A,
max(case when rownum = 2 then received_date end) B,
max(case when rownum = 1 then received_date end) C
FROM
(
SELECT
ROW_NUMBER() OVER(PARTITION BY client_report_id ORDER BY client_report_id,received_date desc) AS rownum,
client_report_id,
received_date
FROM
receipt
) A
WHERE A.rownum IN (1,2,3)
group by client_report_id
) B
WHERE A IS NOT NULL AND B IS NOT NULL AND C IS NOT NULL
Note that this SQL performs the calculation for all database records, not just for a specific one, as shown in the question.
Its return consists of the Client ID and 6 fields. The necessary ones are only the client id and the media field. But I’ve left the others to make it clear.
For it to work, it is assumed that the customer has made at least 3 purchases. If he does less than that, then it will not appear.
Note that although the name of the table and fields does not reflect the question, it is very simple to change it, since it is only a table (Receipt) and two fields (client_report_id and received_date).
Show us a table with the fields.
– Diego Souza
Eu fiz a seguinte query:
SELECT TOP 3 data 
FROM dbo.tab_venda ven 
 INNER JOIN dbo.tab_item_venda iven 
 ON iven.num_venda = ven.num_venda 
WHERE ven.cod_pessoa = 737 
 AND iven.cod_produto = 2111 
ORDER BY ven.data DESC 
 which returns to me: DATA 2015-08-10 00:00:00.000 2015-07-10 00:00:00.000 2015-06-03 00:00:00.000
– Laísa Ferreira Cardoso
You don’t need the average, as I understand it. You need the difference of days between the last three dates, correct?
– cantoni
Yes, this, but I put as average because I need to catch the interval between the dates, for example: Between the date 03/06/2015 as 10/07/2015 is equal to 37 and between 07/10/2015 to 05/10/2015 equal 30, I do the sum of this interval that of 67 and divided by 2 (because they are two intervals, I believe) where the final value would be 33.5 so I will consider that my client usually buys 33 in 33 days.. This is my reasoning right.. If anyone thinks this incorrect please help me. Now I wanted to do this all via bank, it will be right?
– Laísa Ferreira Cardoso
@Laísaferreiracardoso, I updated my answer. I believe you are now doing what you want. Change the fields to those of your model and test, please.
– cantoni