我遇到了让NHibernate执行分页结果分组的问题。我正在尝试从一组数据中获取,在日期范围内获取数据,通过SearchTerm列对过滤的数据组进行分组,并选择具有最新SearchDate的行。所有这些都在分页数据时。
var results = _nHibernateSession.Query<SearchLog>()
.Where(x => x.SearchDate <= DateTime.Now && x.SearchDate >= DateTime.Now.AddDays(-30))
.GroupBy(x => x.SearchTerm)
.Select(g => g.OrderBy(x => x.SearchDate).FirstOrDefault())
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList;
var count = _nHibernateSession.Query<SearchLog>()
.Where(x => x.SearchDate <= DateTime.Now && x.SearchDate >= DateTime.Now.AddDays(-30))
.GroupBy(x => x.SearchTerm)
.Select(g => g.OrderBy(x => x.SearchDate).FirstOrDefault())
.Count();
var results = query.ToList();
生成的查询是
SELECT TOP (20 /* @p0 */)
* /* Replacing selects here with star to reduce lines */
FROM (select search0_.search_id as search1_51_,
search0_.search_term as search7_51_,
search0_.search_date as search9_51_
ROW_NUMBER() OVER(ORDER BY CURRENT_TIMESTAMP) as __hibernate_sort_row
from SearchLog.dbo.SearchLog search0_
where search0_.search_dt <= '2017-04-12T11:29:57' /* @p1 */
and search0_.search_dt >= '2017-03-13T11:29:57' /* @p2 */
group by search0_.search_term) as query
WHERE query.__hibernate_sort_row > 0 /* @p3 */
ORDER BY query.__hibernate_sort_row
正如您所看到的,它没有生成要按其他行分组的SQL,而只是按SearchTerm进行分组,这会抛出错误,说明“某些列在选择列表中无效,因为它不包含在聚合函数中或者GROUP BY子句“。
NHibernate版本: 3.3.3.4001
这是我正在寻找的但是有分页(Skip,Take)
SELECT s.*
FROM SearchLog.dbo.SearchLog s
INNER JOIN (SELECT MAX(id) AS MaxSearchId,
search_term
FROM SearchLog.dbo.SearchLog
WHERE user_id = '123'
AND search_dt <= '2017-04-12T12:09:50'
AND search_dt >= '2017-03-13T12:09:50'
GROUP BY search_term) groupeds
ON s.id = groupeds.MaxSearchId
ORDER BY s.search_dt DESC
值得注意的是,我想计算结果的数量,这也是由group by子句产生的。但是,我不知道如何用这个做一个未来,这样我就可以进行1次DB往返而不是2次,无论如何都可以使这个查询更有效率。
更新 这是我尝试的东西,但似乎仍无法使其正常工作
var distinctQuery =
(
from ds in _nHibernateSession.Query<SearchLog>()
where ds.UserId == userId.ToString() && ds.SearchDate <= DateTime.Now && ds.SearchDate >= DateTime.Now.AddDays(-30)
group ds by ds.SearchTerm into g
select new { NumericalId = g.Max(s => s.NumericalId), SearchTerm = g.Key, SearchDate = g.Max(s => s.SearchDate) }
);
var result =
(
from s in _nHibernateSession.Query<SearchLog>()
join ds in distinctQuery on s.NumericalId equals ds.NumericalId
select s
).ToArray();
我收到错误消息“不支持指定方法”。我只是想做一些不可能的事情吗?