1

我正在尝试使用 NHibernate 标准重新创建类似于以下 SQL 的内容:

select Range, count(*) from (
   select
      case
         when ent.ID between 'A' and 'N' then 'A-M'
         else 'Other'
      end as Range
   from Subject
) tbl
group by tbl.Range

我可以按如下方式创建内部选择:

session.CreateCriteria<Subject>()
   .SetProjection(
      Projections.Conditional(
         Expression.Between("Name", "A", "N"),
         Projections.Constant("A-M"),
         Projections.Constant("Other")))
   .List();

但是,我不知道如何将这些结果按行数分组。

4

1 回答 1

2

这应该工作...

session.CreateCriteria<Subject>()
   .SetProjection(
       Projections.ProjectionList()
          .Add(
             Projections.GroupProperty(
                Projections.Conditional(
                   Restrictions.Between("Name", "A", "N"),
                   Projections.Constant("A-M"),
                   Projections.Constant("Other"))))
        .Add(Projections.RowCount()))
   .List();

...但事实并非如此。所以你可以这样做:

session.CreateCriteria<Subject>()
   .SetProjection(
      Projections.ProjectionList()
         .Add(
            Projections.GroupProperty(
               Projections.SqlProjection(
                  @"case
                       when Name between 'A' and 'N' then 'A-M'
                       else 'Other' 
                    end as Range",
                  new[] { "Range" },
                  new[] { TypeFactory.GetStringType(5) })))
         .Add(Projections.RowCount()))
   .List();
于 2010-05-18T18:46:56.240 回答