title: Group by dynamic time period
body: <p>For my problem I'll try to create a simplified example.<br>
  Table "order":</p>
  
  <pre><code>ID |    date    | client | product | product_limit_period (in months)
  1  | 2015-01-01 | Bob    | table   | 1
  2  | 2015-01-31 | Bob    | table   | 1
  3  | 2015-02-01 | Bob    | table   | 1
  4  | 2015-01-01 | Mary   | lamb    | 12
  5  | 2015-06-01 | Mary   | lamb    | 12
  6  | 2016-01-01 | Mary   | lamb    | 12
  7  | 2016-12-31 | Mary   | lamb    | 12
  </code></pre>
  
  <p>This is the result, I'd like to get:</p>
  
  <pre><code>client | product | group | count
  Bob    | table   | 1     | 2       #ID 1, 2
  Bob    | table   | 2     | 1       #ID 3
  Mary   | lamb    | 3     | 2       #ID 4, 5
  Mary   | lamb    | 4     | 2       #ID 6, 7
  </code></pre>
  
  <p>Every product has a limit and a limit period (in months). I need to be able to see if there are any clients that have ordered a product more than its limit allows in a certain period. <strong>The period in months might be 1 month or several years in months.</strong> It is possible that the period is 1 month, 12 months, 24 months, ... until 108 months (9 years).</p>
  
  <p>I feel like I need to use some combination of window functions and group by. But I haven't figured out how.</p>
  
  <p>I'm using postgres 9.1. Please let me know if there is any more information I should provide.</p>
  
  <p>Any help is appreciated, even just pointing me to the right direction!</p>
  
  <p><strong>Edit:</strong><br>
  To clarify how the grouping works: The limit period starts with the first order. Bob's first order is 2015-01-01 and so this period ends with 2015-01-31. 2015-02-01 starts a second period. <strong>A period always starts with the first day of a month and ends with the last day of a month.</strong></p>