我通过FluentNHibernate映射了以下域
class Point
{
public int Id { get; set; }
public string Label { get; set; }
}
class PointData
{
public int Id { get; set; }
public DateTime Hour { get; set; }
public decimal Value { get; set; }
public Point Location { get; set; }
public DateTime Available { get; set; } // Data arrival (data tracking)
}
PointData表会频繁更新一小时插入新值(不支持更新),但并非所有点都以相同的频率写入PointData。
我需要在startTime和endTime之间以及timeOfSnapshot(可用)之前的所有小时内获得每点Point的最新PointData。
到目前为止,我使用group by使用Linq到Nhibernate的查询不起作用:
Query.Where(x => x.Available <= available && x.Hour >= startHour && x.Hour < endHour)
.OrderByDescending(x => x.Available)
.GroupBy(x => new {x.Location, x.Hour})
.Select(g => g.First())
.ToList();
到目前为止,所有搜索都只提出了SQL查询,这不是我想要的。
帮助是适当的
答案 0 :(得分:1)
使用原始行按结果加入组并返回行:
rows.Join(
rows.GroupBy(x => new {x.Location, x.Hour}),
x => new {x.Location, x.Hour, x.Available},
g => new {g.Key.Location, g.Key.Hour, Available = g.Max(p=>p.Available)},
(x1,g1) => x1
)
打开一个分析器,你会看到这个sql:
SELECT [t0].*
FROM [rows] AS [t0]
INNER JOIN (
SELECT MAX([t1].[Available]) AS [value], [t1].[Location], [t1].[Hour]
FROM [rows] AS [t1]
GROUP BY [t1].[Location], [t1].[Hour])
AS [t2] ON (
[t0].[Location] = [t2].[Location])
AND ([t0].[Hour] = [t2].[Hour])
AND ([t0].[Available] = [t2].[value]
)
答案 1 :(得分:0)
在分组后,您无法提取比分组键或聚合中使用的列更多的列。如果我正确理解你的问题,通常的模式是使用一个子查询来选择感兴趣的行的标识符,然后使用外部查询来获取这些行的所有列。尝试这样的事情:
var latestPointId =
Query.Where(x => x.Available <= available && x.Hour >= startHour && x.Hour < endHour)
.OrderByDescending(x => x.Available)
.GroupBy(x => new {x.Location, x.Hour})
.Select(g => g.Max(pd => pd.Id));
session.Query<PointData>
.Where(pd => latestPointId.Contains(pd.Id)
.ToList();