我有 2 个表要使用 join
查询,即 loans
和 amortizations
table 。Loans
表有很多摊销,所以 loans.id
是对 amortizations.loan_id
的引用在 amortizations
table 。Loan id:3
在 amortizations table
中存在两次,每个都有一个 value=10,800
.Loan id:5
在 amortizations table
中也存在两次,每个都有一个 value=11,100
Loan id:11
也是如此在 amortizations table
中也存在两次每个人都有一个 value=5400
.
当你把它加起来时,total
是 54,600
.但我希望 id 是不同的,这样值就不会增加两次。所以总数将等于 27,300
.我在下面的现有查询返回 54,600
值而不是 27,300
甚至使用 distinct()
在 Laravel 中。我将如何实现这一目标?Controller query
$oneToThirtyDue = Amortization::distinct('amortizations.loan_id')
->join('loans', 'loans.id', '=', 'amortizations.loan_id')
->select('loans.loan_type',\DB::raw('SUM(loans.loan_balance) as total_val'))
->where('amortizations.payment_status',0)
->where('amortizations.schedule', '<', date('Y-m-d'))
->where('amortizations.past_due', '<=', 30)
->groupBy('loans.loan_type')
->orderBy('loans.loan_type')
->get();
请帮忙。非常感谢。
最佳答案
$idsDue = Amortization::distinct()
->select('loan_id')
->where('payment_status',0)
->where('schedule', '<', date('Y-m-d'))
->where('past_due', '<=', 30)
->get();
$oneToThirtyDue = Loan::select('loan_type',\DB::raw('SUM(loan_balance) as total_val'))
->whereIn('id',$idsDue)
->groupBy('loan_type')
->orderBy('loan_type')
->get();
关于sql - 使用 join 和 distinct 的 Laravel 求和查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57760311/