title: How to sum the total amount for the last 12 months using parameters
body: <p>I want to SUM up the last 12 months values from a sql query.
  <br>
  The problem is to sum up the last 12 months, instead of taking just the whole year.
  <br>
  So when I SELECT March 2000 as default in my parameter, 
  <br> I want the query to SUM up: from March 1999-March 2000.</p>
  
  <p>This is what I got so far:</p>
  
  <pre><code>SELECT Name, SUM(sales) as totalsales, year_month
  FROM Total_Sales
  WHERE 
  (year_month = @year_month)
  GROUP BY Name, year_month
  </code></pre>
  
  <p>Thanks for any help!</p>
  
  <p>--EDIT--</p>
  
  <pre><code>SELECT Name, SUM(sales) as totalsales, year_month
  FROM Total_Sales
  WHERE 
  (year_month &gt;= @From) AND 
  (year_month &lt;= @To)
  GROUP BY Name, year_month
  </code></pre>
  
  <p>Added this after suggestions from "Steve Morgan" 
  <BR>
  Can we add a average for the last 12 months somehow without selecting 12 months in the parameters.
  Letting the "@From" parameter decide on start value. Something like: AVG(@From -12 months)??</p>
  
  <p>Thanks again for the help!</p>
  
  <p>--EDIT 2--</p>
  
  <p>The <strong>ROW_NUMBER()</strong> function is very handy to solve this problem.
  My query looks like this now:</p>
  
  <pre><code>SELECT  Name, SUM(sales)
  FROM    
  (               
  SELECT  rn = ROW_NUMBER() OVER (PARTITION BY Name ORDER BY year, year_month)
  , Name
  , sales = SUM(sales)
  FROM     Total_Sales ts
  WHERE
  (year_month&gt;= @From) AND 
  (year_month&lt;= @To)
  GROUP BY
  Name
  , year
  , year_month
      ) ts 
  WHERE
  rn &lt;= 12    
  
  GROUP BY
  Name  
  </code></pre>