获取laravel 5和mysql中groupby对象的第一个和最后一个值

时间:2016-04-01 03:47:02

标签: php mysql laravel-5

我有一张名为收入的表。

case str of
   "+" => print("PLUS MINUS")
 | "-" => print("PLUS MINUS")
 | "*" => print("MULT DIV")
 | "/" => print("MULT DIV")

我想要做的是查询这些并按+----+-------------+---------------------+--------+--------+--------+-----------+---------------------+---------------------+ | id | employee_id | date | gross | income | credit | comission | created_at | updated_at | +----+-------------+---------------------+--------+--------+--------+-----------+---------------------+---------------------+ | 1 | 1 | 2016-03-30 19:21:09 | 100.00 | 29.00 | 11.00 | 60.00 | 2016-03-31 19:21:46 | 2016-03-31 19:21:46 | | 2 | 1 | 2016-03-31 19:24:44 | 110.00 | 43.00 | 1.00 | 60.00 | 2016-03-31 19:24:56 | 2016-03-31 19:24:56 | | 3 | 2 | 2016-03-31 21:44:09 | 77.00 | 30.80 | 0.00 | 60.00 | 2016-03-31 21:44:19 | 2016-03-31 21:44:19 | +----+-------------+---------------------+--------+--------+--------+-----------+---------------------+---------------------+ 对其进行分组,我希望它开始的日期和结束日期。我得到的是

employee_id

这始终返回该员工的第一个日期。例如,$records = Income::whereBetween('date', [$start, $end]) ->groupBy('employee_id') ->selectRaw('store_incomes.* , sum(gross) as total_gross , sum(income) as total_income, sum(credit) as total_credit') ->get(); 始终返回employee_id 1的日期。我想要的是获取每个2016-03-30 19:21:09的第一个和最后一个日期,因此employee_id的开始日期为employee id 1,结束日期为2016-30-30。有没有办法在没有杂乱的手动代码的情况下做到这一点?

对于当前代码,我的输出是:

2016-03-31

我的预期输出包括另外两个值([ {"id":"1","employee_id":"1","date":"2016-03-30 19:21:09","gross":"100.00","income":"29.00","credit":"11.00","comission":"60.00","created_at":"2016-03-31 19:21:46","updated_at":"2016-03-31 19:21:46","total_gross":"210.00","total_income":"72.00","total_credit":"12.00"}, {"id":"3","employee_id":"2","date":"2016-03-31 21:44:09","gross":"77.00","income":"30.80","credit":"0.00","comission":"60.00","created_at":"2016-03-31 21:44:19","updated_at":"2016-03-31 21:44:19","total_gross":"77.00","total_income":"30.80","total_credit":"0.00"} ] start_date):

end_date

1 个答案:

答案 0 :(得分:1)

您想要的原始MySQL查询是这样的:

SELECT MIN(date) AS start_date, MAX(date) AS end_date, store_incomes.*,
    SUM(gross) AS total_gross , SUM(income) AS total_income, SUM(credit) AS total_credit
FROM income
GROUP BY employee_id

要在Laravel中执行此操作,只需将MIN()MAX()添加到原始查询中:

$records = DB::Income
               ->selectRaw('store_incomes.* , min(date) as start_date, max(date) as end_date, sum(gross) as total_gross , sum(income) as total_income, sum(credit) as total_credit')
               ->groupBy('employee_id')
               ->get();