【发布时间】:2019-09-08 08:44:58
【问题描述】:
我有一张表,上面有名字、negeri 以及开始服务和结束服务的年份。我想得到一个人在一个州服务的年数:
ID | Name | State | yearstart | yearend
-----------------------------------------------------------
1 | Tom | Kedah | 2001 | 2002
1 | Tom | Kedah | 2003 | 2007
2 | Anne | Melaka | 2008 | 2012
2 | Anne | Melaka | 2013 | 2018
3 | Bill | KL | 2000 | 2001
我已经试过了。但它只计算年数并列出所有人(姓名和状态重复)。
$query = DB::table('itemregistrations')
->join('state', 'itemregistrations.StateID', '=', 'state.StateID')
->select('itemregistrations.name');
if($request->input('negeri_perkhidmatan') != '') {
$query->join('itemregistrationpangkat', 'itemregistrationpangkat.itemRegistrationID', '=', 'itemregistrations.itemRegistrationID')
->where('itemregistrationpangkat.StateID', $request->input('negeri_perkhidmatan'));
}
if(request('tempoh_negeri')) {
$query->whereRaw('yearend - yearstart >= ?', [request('tempoh_negeri')]);
}
结果显示:
ID | Name | State | years
---------------------------------------
1 | Tom | Kedah | 1
1 | Tom | Kedah | 4
2 | Anne | Melaka | 4
2 | Anne | Melaka | 5
3 | Bill | KL | 1
结果应该是:
ID | Name | State | years
---------------------------------------
1 | Tom | Kedah | 5
2 | Anne | Melaka | 9
3 | Bill | KL | 1
浏览器中显示的结果是使用 ajax 获取的。我这里就不放了。
【问题讨论】:
-
只需将
groupBy('ID')添加到您的查询中 -
我不能简单地使用 groupby 并且我之前已经尝试过,但它失败了。因为它不计算但选择具有不同值的列。查看当前的sql代码。
-
你的代码是不是像这样
$query->whereRaw('yearend - yearstart >= ?', [request('tempoh_negeri')]).groupBy('ID'); -
$query->whereRaw('yearend - yearstart >= ?', [request('tempoh_negeri')])->groupBy('itemregistrations.ItemRegistrationID');
-
怎么样
$query->whereRaw('yearend - yearstart >= ?', [request('tempoh_negeri')])->groupBy('ID')->select('ID,Name,State,SUM(years) as years');
标签: mysql sql laravel sum laravel-query-builder