title: Get last N elements for each group
body: <p>What I'm trying to do is grab the last N elements (for my example 3) for each grouping in the table. My table is:</p>
  
  <pre><code>create table application_sessions
  (
      application_session_id int identity(1,1) primary key,
      session_type_id int not null references session_types(session_type_id),
      start_ts datetime not null,
      end_ts datetime null,
      is_successful bit not null default 0
  )
  </code></pre>
  
  <p>In this case, I'm trying to get the last 3 entries in the table (ordered by start_ts) for each session_type_id. To do this in SQL, I would run this:</p>
  
  <pre><code>;with ranking as
  (
      select *, row_number() over (partition by session_type_id order by start_ts desc) as rn
      from application_sessions
  )
  select * from ranking
  where rn &lt;= 3
  </code></pre>
  
  <p>I'm having some issues using NHibernate with fetching these records from the database in this way. What would be the best way to do this given the Entity below (SessionType is an enum)?</p>
  
  <pre><code>public class ApplicationSession
  {
      public virtual int Id { get; set; }
      public virtual SessionType SessionType { get; set; }
      public virtual DateTime StartTimestamp { get; set; }
      public virtual DateTime? EndTimestamp { get; set; }
      public virtual bool IsSuccessful { get; set; }
  }
  </code></pre>
  
  <p>My (failing) first attempt was this:</p>
  
  <pre><code>public IList&lt;ApplicationSession&gt; GetLastNGroupedSessions(int count)
    {
       return _session.Query&lt;ApplicationSession&gt;()
                         .GroupBy(x =&gt; x.SessionType)
                         .SelectMany(y =&gt;
                                 y.OrderByDescending(z =&gt; z.StartTimestamp)
                                  .Take(count))
                         .ToList();
     }
  </code></pre>
  
  <p>This yields the exception:
  Query Source could not be identified: ItemName = y, ItemType = System.Linq.IGrouping`2[RIMS.ECMS.BusinessObjects.Local.Models.SessionType,RIMS.ECMS.BusinessObjects.Local.Models.ApplicationSession], Expression = from IGrouping`2 y in {value(NHibernate.Linq.NhQueryable`1[RIMS.ECMS.BusinessObjects.Local.Models.ApplicationSession]) => GroupBy([x].SessionType, [x])}</p>