简体   繁体   English

每个唯一列值限制一行,按最大列值选择

[英]Limit one row per unique column value selecting by max column value

I'm trying to select the most recent WorkOrder for each Customer . 我正在尝试为每个Customer选择最新的WorkOrder I've used ORDER BY and GROUP BY , but the result returned is not the newest WorkOrder . 我使用过ORDER BYGROUP BY ,但是返回的结果不是最新的WorkOrder

Table Structure: 表结构:

WorkOrder
    id
    customer_id
    create_date
    ...

Sample Data: 样本数据:

WorkOrder.id    WorkOrder.customer_id   WorkOrder.create_date   ...
1               1                       2012-01-01 12:00:00
2               1                       2016-06-29 12:00:00
3               2                       2015-05-05 12:00:00

Desired Result: 所需结果:

WorkOrder.id    WorkOrder.customer_id   WorkOrder.create_date   ...
2               1                       2016-06-29 12:00:00
3               2                       2015-05-05 12:00:00

Current Code: 当前代码:

$query = DB::table('WorkOrder')
    ->orderBy('WorkOrder.create_date', 'desc')
    ->groupBy('WorkOrder.customer_id');

// select * from `WorkOrder` group by `WorkOrder`.`customer_id` order by `WorkOrder`.`create_date` desc

Current Result: 当前结果:

WorkOrder.id    WorkOrder.customer_id   WorkOrder.create_date   ...
1               1                       2012-01-01 12:00:00
3               2                       2015-05-05 12:00:00

使用最大功能

SELECT WorkOrder.id, WorkOrder.customer_id, MAX(WorkOrder.create_date) FROM `WorkOrder` GROUP BY `WorkOrder`.`customer_id` ORDER BY `WorkOrder`.`create_date` DESC

Try this: 尝试这个:

SELECT * FROM WorkOrder 
WHERE (customer_id, create_date) IN 
      (SELECT customer_id, MAX(create_date) FROM WorkOrder
       GROUP By customer_id)
ORDER BY ...

I tend to do this with a correlated subquery: 我倾向于使用相关的子查询来做到这一点:

select wo.*
from workorder wo
where create_date = (select max(wo2.create_date)
                     from workorder wo2
                     where wo2.customer_id = wo.customer_id
                    );

That advantage to this approach over using a group by in the subquery: 与在子查询中使用group by相比,该方法的优势在于:

  • If you have other filters in the where clause, then this will only look up the values on a reduced set of rows. 如果where子句中有其他过滤器,则只会在减少的行集中查找值。
  • It can use an index for the lookup, without having to first do an aggregation. 它可以使用索引进行查找,而不必首先进行聚合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM