【问题标题】:HQL select ID of entity with max value within groupHQL选择组内具有最大值的实体的ID
【发布时间】:2012-10-30 17:01:17
【问题描述】:

我有这个小实体

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 == 更新的Order 这个:

select o 
from Order o 
where o.Id in 
   (select max(o2.Id) 
    from Order o2 
    group by o2.ProductId);

对我有用。有没有更好的解决方案?

【问题讨论】:

  • 并非总是如此,如果有人更改/更新订单日期,那么您的查询将不会返回正确的结果。
  • 100% 正确 ;-) 因此我要求更好的解决方案

标签: c# sql hibernate hql


【解决方案1】:

尝试 self join 而不是 in 查询以获得更好的性能。

【讨论】:

    【解决方案2】:

    查询需要优化,但它适合你。

    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()));
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-28
      • 2021-08-10
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2013-01-02
      • 2019-12-19
      相关资源
      最近更新 更多