2011-02-01 53 views
1

我有SQL,我想在標準API來編寫:如何組由NHibernate的範圍與標準API

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 

回答

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位,但你總是可以排序客戶端。

+0

我自己結束了幾乎完全相同的代碼。而且,作品也很好。一兩件事,我加入是VAR caseString = @「CASE WHEN TOTAL_PAGES = 0 THEN 'A0頁' WHEN 1和3之間TOTAL_PAGES THEN 'B1-3頁' WHEN在4和6 THEN TOTAL_PAGES「C 4-6頁'...對PageRanges的字母表進行良好的排序 – 2011-02-03 08:32:10