Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
eshiel3
Starting Member
2 Posts |
Posted - 2015-03-18 : 14:50:14
|
I have a table with some examples below. I need to identify records where: 1. the person has 3 or more consecutive months ordered.2. I then need to exclude the first and last month and capture only those Months in between.PERSON ID MONTH ORDEREDJD12345 4JD12345 7JD12345 8 Note: JD12345 should be excluded entirelyJD12348 5JD12348 6 this record should be capturedJD12348 7 this record should be capturedJD12348 8 this record should be capturedJD12348 9JD12363 12 Note: JD12363 should be excluded entirelyJD12374 3JD12374 4 this record should be capturedJD12374 5 |
|
eshiel3
Starting Member
2 Posts |
Posted - 2015-03-18 : 17:00:50
|
Problem solved:CREATE TABLE #Sample( [PERSON_ID] char(7), [MONTH_ORDERED] int)INSERT INTO #SampleSELECT 'JD12345','4' UNION ALLSELECT 'JD12345','7' UNION ALLSELECT 'JD12345','8' UNION ALLSELECT 'JD12348','5'UNION ALLSELECT 'JD12348','6' UNION ALLSELECT 'JD12348','7' UNION ALLSELECT 'JD12348','8' UNION ALLSELECT 'JD12348','9' UNION ALLSELECT 'JD12363','12' UNION ALLSELECT 'JD12374','3' UNION ALLSELECT 'JD12374','4' UNION ALLSELECT 'JD12374','5' ;WITH CTE AS( SELECT *, MONTH_ORDERED - ROW_NUMBER() OVER(PARTITION BY PERSON_ID ORDER BY MONTH_ORDERED) grouper, ROW_NUMBER() OVER(PARTITION BY PERSON_ID ORDER BY MONTH_ORDERED) rnfirst, ROW_NUMBER() OVER(PARTITION BY PERSON_ID ORDER BY MONTH_ORDERED DESC) rnlast FROM #Sample) SELECT [PERSON_ID], [MONTH_ORDERED]FROM CTE WHERE rnfirst > 1AND rnlast > 1AND PERSON_ID IN(SELECT PERSON_ID FROM CTE GROUP BY PERSON_ID, grouper HAVING COUNT(*) >= 3)ORDER BY [PERSON_ID], [MONTH_ORDERED]GODROP TABLE #Sample |
|
|
Kristen
Test
22859 Posts |
Posted - 2015-03-19 : 03:53:30
|
quote: Originally posted by eshiel3 Problem solved:
Does it matter if the "months" are 11, 12, 1 ? They would be "consecutive" presumably? |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2015-03-19 : 06:07:32
|
quote: Originally posted by Kristen
quote: Originally posted by eshiel3 Problem solved:
Does it matter if the "months" are 11, 12, 1 ? They would be "consecutive" presumably?
May be. In that case it is better to use YYYYMM valueMadhivananFailing to plan is Planning to fail |
|
|
|
|
|
|
|