doufu7464 2017-06-04 08:50
浏览 316
已采纳

如何获取按日期排序的一条记录

I have a table like this:

id    product_id   price      date
1       1001        100     2017-05-29
2       1005        101     2017-03-30
3       1001        102     2017-03-30
4       1003        106     2017-06-07
5       1005        106     2017-04-30

I want to group by product_id and get only one latest product for each product_id. I also have a min and max price variable which should be applied to the price column.

the result of my query should be:

1       1001        100     2017-05-29
4       1003        106     2017-06-07
5       1005        106     2017-04-30

Is it possible by SQL or I should use application side?

  • 写回答

2条回答

  • dongrui6787 2017-06-04 09:00
    关注

    If you want to order results by date, just use orderBy():

    Model::orderBy('date_column', 'desc')->whereBetween('price', [$min, $max])->groupBy('product_id')->take(3)->get();
    

    Or it's shortcuts latest() and oldest():

    Model::latest('date_column')->...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog