I have a table with columns: MONTH, YEAR, PROJECT_ID, STATUS.
Status can be:
- R (red).
- A (amber).
- G (green).
- N (not started).
- C (completed).
I want to know how many projects completed in a given month i.e. :
where STATUS changed from anything that is NOT C to C;
It sounds simple…!
It’s easy to find when any given project completed with:
SELECT TOP 1 MONTH,YEAR,PROJECT_ID FROM Table WHERE PROJECT_ID=9236 AND RAG='C'
ORDER BY YEAR ASC, MONTH ASC
But given year = 2011 and month = 8 (for example), I have no idea how to find the number of projects that had status='C' for the first time that month. Any ideas?
Edit: projects are still included as rows with status='C' after they complete, so I can’t just count the Cs as that will return the number of projects that completed in this AND previous months (hence the chronological ordering and select top 1).
Sample data for 10/2010 to 01/2011 months:
Month | Year | Project | Status
-------------------------------
10 | 2010 | A | G
11 | 2010 | A | C
12 | 2010 | A | C
1 | 2011 | A | C
10 | 2010 | B | R
11 | 2010 | B | R
12 | 2010 | B | R
1 | 2011 | B | R
10 | 2010 | C | G
11 | 2010 | C | G
12 | 2010 | C | G
1 | 2011 | C | C
10 | 2010 | D | A
11 | 2010 | D | C
12 | 2010 | D | C
1 | 2011 | D | C
^ Projects A and D was completed in 11/2010. Project B hasn’t changed to completed in any of the four months shown. Project C was completed in 01/2011. {Month,Year,Project} is the primary key.
So, inputs and outputs would be:
10/2010 => 0
11/2010 => 2 (because of A and D)
12/2010 => 0
1/2011 => 1 (because of C)
This will give you the counts you are looking for
The inner query determines the date the project closed, so you are finding all projects which closed this month…