Note that there are some explanatory texts on larger screens.

plurals
  1. POSimple SQL Server COUNT query (counting changes to values in a column)
    primarykey
    data
    text
    <p>I have a table with columns: <code>MONTH</code>, <code>YEAR</code>, <code>PROJECT_ID</code>, <code>STATUS</code>.</p> <p>Status can be:</p> <ul> <li><strong>R</strong> (red).</li> <li><strong>A</strong> (amber).</li> <li><strong>G</strong> (green).</li> <li><strong>N</strong> (not started).</li> <li><strong>C</strong> (completed).</li> </ul> <p>I want to know how many projects completed in a given month i.e. :</p> <pre><code>where STATUS changed from anything that is NOT C to C; </code></pre> <p>It sounds simple...!</p> <p>It's easy to find when any given project completed with:</p> <pre><code>SELECT TOP 1 MONTH,YEAR,PROJECT_ID FROM Table WHERE PROJECT_ID=9236 AND RAG='C' ORDER BY YEAR ASC, MONTH ASC </code></pre> <p>But given <code>year = 2011</code> and <code>month = 8</code> (for example), I have no idea how to find the number of projects that had <code>status='C'</code> for the first time that month. Any ideas?</p> <p><strong>Edit:</strong> projects are still included as rows with <code>status='C'</code> 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).</p> <p><strong>Sample data for 10/2010 to 01/2011 months:</strong></p> <pre><code>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 </code></pre> <p>^ 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.</p> <p>So, inputs and outputs would be:</p> <pre><code>10/2010 =&gt; 0 11/2010 =&gt; 2 (because of A and D) 12/2010 =&gt; 0 1/2011 =&gt; 1 (because of C) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload