如何使用条件api按照nhibernate中的范围进行分组

时间:2011-02-01 11:55:00

标签: nhibernate criteria-api

我想在Criteria api中写一些SQL:

SELECT CASE 
WHEN total_pages = 0 THEN '0 pages'
WHEN total_pages BETWEEN 1 AND 3 THEN '1-3 pages'
WHEN total_pages BETWEEN 4 AND 6 THEN '4-6 pages'
WHEN total_pages > 6 THEN '7 + pages'
END AS pagerange, sum(total_pages) AS 'Total'
FROM dbo.connector_log_entry
GROUP BY 
CASE 
WHEN total_pages = 0 THEN '0 pages'
WHEN total_pages BETWEEN 1 AND 3 THEN '1-3 pages'
WHEN total_pages BETWEEN 4 AND 6 THEN '4-6 pages'
WHEN total_pages > 6 THEN '7 + pages'
END
ORDER BY pagerange

1 个答案:

答案 0 :(得分:0)

var groupBy = @"
    CASE
      WHEN total_pages = 0 THEN '0 pages'
      WHEN total_pages BETWEEN 1 AND 3 THEN '1-3 pages'
      WHEN total_pages BETWEEN 4 AND 6 THEN '4-6 pages'
      WHEN total_pages > 6 THEN '7 + pages'
    END";
var pagerange = Projections.SqlGroupProjection(groupBy + " pagerange",
                                               groupBy,
                                               new[] { "pagerange" },
                                               new[] { NHibernateUtil.String });
var results = session.CreateCriteria<ConnectorLogEntry>()
                     .SetProjection(pagerange,
                                    Projections.Sum("TotalPages"))
                     .List();

这假定您的类名为ConnectorLogEntry,而映射到total_pages列的属性称为TotalPages

我欠你ORDER BY位,但你总是可以对客户端进行排序。