繁体   English   中英

获取每个组的最后N个元素

[英]Get last N elements for each group

我想做的是为表中的每个分组获取最后的N个元素(对于我的示例3)。 我的桌子是:

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
)

在这种情况下,我试图为每个session_type_id获取表中的最后3个条目(按start_ts排序)。 为此,我将运行以下命令:

;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 <= 3

我在使用NHibernate以这种方式从数据库中获取这些记录时遇到了一些问题。 给定下面的实体(SessionType是枚举),这样做的最佳方法是什么?

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; }
}

我(失败)的第一次尝试是:

public IList<ApplicationSession> GetLastNGroupedSessions(int count)
  {
     return _session.Query<ApplicationSession>()
                       .GroupBy(x => x.SessionType)
                       .SelectMany(y =>
                               y.OrderByDescending(z => z.StartTimestamp)
                                .Take(count))
                       .ToList();
   }

这产生异常:无法识别查询源:ItemName = y,ItemType = System.Linq.IGrouping`2 [RIMS.ECMS.BusinessObjects.Local.Models.SessionType,RIMS.ECMS.BusinessObjects.Local.Models.ApplicationSession] ,表达式=来自{值(NHibernate.Linq.NhQueryable`1 [RIMS.ECMS.BusinessObjects.Local.Models.ApplicationSession])=> GroupBy([x] .SessionType,[x])}中IGrouping`2 y

因此,它可能不是“最佳”解决方案,但它是可行的解决方案。 我的一位同事指出,NHibernate允许您使用CreateSQLQuery直接执行SQL。 这是我想出的解决方案,以防万一其他人遇到此类问题。

  public IList<ApplicationSession> GetLastNGroupedSessions(int count)
  {

     var sqlQuery = string.Format(@";with ranking as
     (
     select *, row_number() over (partition by session_type_id order by start_ts desc) as rn
     from application_sessions
     )
     select app.application_session_id,
        app.session_type_id,
        app.start_ts,
        app.end_ts,
        app.is_successful 
     from ranking as app
     where rn <= {0}", count);

     return _session.CreateSQLQuery(sqlQuery)
        .AddEntity("app", typeof(ApplicationSession))
        .List<ApplicationSession>();
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM