C# HQL选择组内具有最大值的实体的ID
我有一个小实体C# HQL选择组内具有最大值的实体的ID,c#,sql,hibernate,hql,C#,Sql,Hibernate,Hql,我有一个小实体 class Order { public long Id; public DateTime Date; public long ProductId; } 我想在按ProductId分组的订单中选择具有MAX(Date)的实体的Id。 对(MAX(Date),ProductId)不是唯一的,因此此查询错误: select o.Id from Order o where o.Date = (select max(o2.Date) fro
class Order
{
public long Id;
public DateTime Date;
public long ProductId;
}
我想在按ProductId
分组的订单中选择具有MAX(Date)
的实体的Id
。
对(MAX(Date)
,ProductId
)不是唯一的,因此此查询错误:
select o.Id
from Order o
where o.Date =
(select max(o2.Date)
from Order o2
where o2.ProductId = o.ProductId);
你有什么想法吗
基本上,我想要的是从组中获取最新的订单,所以如果我假设更大的Id
==更新的订单
这个:
select o
from Order o
where o.Id in
(select max(o2.Id)
from Order o2
group by o2.ProductId);
这对我有用。有更好的解决方案吗?尝试自连接而不是在查询中,以获得更好的性能。查询中需要进行优化,但它适合您
List<Order> orders = GetOrders();
var result = from o in orders
group o by new { o.ProductId } into ordGrouping
let MaxOrderDate = ordGrouping.Max(od=>od.Date)
let OrderID = ordGrouping.First(od=>od.Date.Equals(MaxOrderDate)).Id
select new
{
ProductId = ordGrouping.Key.ProductId,
OrderId = OrderID,
OrderDate = MaxOrderDate
};
foreach (var item in result)
{
Console.WriteLine(string.Format("Product ID:{0}, OrderId: {1} Date: {2}", item.ProductId, item.OrderId, item.OrderDate.ToLongDateString() + item.OrderDate.ToLongTimeString()));
}
List orders=GetOrders();
var结果=从订单中的o开始
通过新的{o.ProductId}将o分组到ordGrouping中
让MaxOrderDate=ordGrouping.Max(od=>od.Date)
让OrderID=ordGrouping.First(od=>od.Date.Equals(MaxOrderDate)).Id
选择新的
{
ProductId=ordGrouping.Key.ProductId,
OrderId=OrderId,
OrderDate=MaxOrderDate
};
foreach(结果中的var项目)
{
Console.WriteLine(string.Format(“产品ID:{0},订单ID:{1}日期:{2}”,item.ProductId,item.OrderId,item.OrderDate.ToLongDateString()+item.OrderDate.ToLongTimeString());
}
情况并非总是如此,如果有人更改/更新订单日期,您的查询将不会返回正确的结果。100%正确;-)因此,我要求一个更好的解决方案