I have been creating a date range, but in some cases a have a problem:
This is what I have: TABLE_1
date customer_id status total
---- ------------- -------- -------
20120201 1 a 10
20120202 1 a 20
20120203 1 b 20
20120204 1 b 20
20120205 1 a 20
20120206 1 a 20
20120201 2 d 30
20120202 2 e 40
After the execution of my procedure, I have this: TABLE_2
customer_id status start_date end_date
------------- -------- ----------- ---------
1 a 20120201 NULL
1 b 20120203 20120131
2 d 20120201 20120201
2 e 20120202 NULL
But this is what i want, a table with date ranges based on customer_id and status (end_date represents register with most recent date): TABLE_3
customer_id status start_date end_date
------------- -------- ----------- ---------
1 a 20120201 20120202
1 b 20120203 20120204
1 a 20120205 NULL
2 d 20120201 20120201
2 e 20120202 NULL
My store procedure look like this:
;WITH TEMP AS (
SELECT
Date
customer_id
status
FROM table_1
GROUP BY
date,
customer_id,
status
)
,TEMP2 AS (
SELECT
ID = ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY MAX(date) DESC),
start_date = MIN(date),
end_date = MAX(date),
[customer_id],
[status]
FROM TEMP
GROUP BY
[customer_id],
[status]
)
SELECT
A.customer_id,
A.status,
A.start_date,
end_date = DATEADD(DAY,-1,B.start_date)
FROM TEMP2 A
LEFT JOIN TEMP2 B
ON A.customer_id = B.customer_id
AND A.ID = B.ID + 1
I know my error is in the creation of CTE TEMP2, because this code can´t discriminate for a customer_id with a status with two occurrences in different ranges of time, based on the ‘group by’ sentence
I can´t figure out how to do that…
Try this. Hope it works now.