title: Summarize days per month based on date ranges
body: <p>Being primarily a C# developer, I'm scratching my head when trying to create a pure T-SQL based solution to a problem involving summarizing days/month given a set of date ranges.</p>
  
  <p>I have a set of data looking something like this:</p>
  
  <pre><code>UserID  Department  StartDate   EndDate
  ======  ==========  ==========  ==========
  1       A           2011-01-02  2011-01-05
  1       A           2011-01-20  2011-01-25
  1       A           2011-02-25  2011-03-05
  1       B           2011-01-21  2011-01-22
  2       A           2011-01-01  2011-01-20
  3       C           2011-01-01  2011-02-03
  </code></pre>
  
  <p>The date ranges are non-overlapping, may span several months, there may exist several ranges for a specific user and department within a single month.
  What I would like to do is to summarize the number of days (inclusive) per user, department, year and month, like this (with reservations for any math errors in my example...):</p>
  
  <pre><code>UserID  Department  Year  Month  Days
  ======  ==========  ====  =====  ====
  1       A           2011  01     10
  1       A           2011  02     4
  1       A           2011  03     5
  1       B           2011  01     2
  2       A           2011  01     20
  3       C           2011  01     31
  3       C           2011  02     3
  </code></pre>
  
  <p>This data is going into a new table used by reporting tools.
  I hope the problem description is clear enough, this is my first posting here, be gentle :-)</p>
  
  <p>Thanks in advance!</p>