是否可以使用查询构建器在Eloquent中创建嵌套选择?我有问题,我需要在我的表的一列上分组和使用总和,但该列显示为借方或贷方,并取决于另一列值。我需要再分组一次以获得一行中的两个总和。
$columns=array( DB::raw('left(archive_ledgers.account,3) as account'),
DB::raw('(case when archive_ledgers.booking_type=1 then sum(archive_ledgers.amount) else 0 end) as debit'),
DB::raw('(case when archive_ledgers.booking_type!=1 then sum(archive_ledgers.amount) else 0 end) as credit')
);
ArchiveLedger::where('accounts.account_type', '<=', $accounts['to'])
->join('accounts',function($join){
$join->on('archive_ledgers.account','=','accounts.account');
})
->join('orders',function($join){
$join->on('orders.id','=','archive_ledgers.order_id');
})
->where('archive_ledgers.account', '>=', $accounts['from'])
->where('document_date', '<=', Input::get('dateTo'))
->where('document_date', '>=', Input::get('dateFrom'))
->select($columns)
->orderBy('archive_ledgers.booking_type',DB::raw('left(archive_ledgers.account,3)'))
->groupBy('archive_ledgers.booking_type',DB::raw('left(archive_ledgers.account,3)'));
我需要对此查询提供的结果进行选择
select `account`, sum(s1.owes) as owes, sum(s1.asks) as asks, s1.owes - s1.asks as total from (select left(archive_ledgers.account,3) as account, (case when archive_ledgers.booking_type=1 then sum(archive_ledgers.amount) else 0 end) as owes, (case when archive_ledgers.booking_type!=1 then sum(archive_ledgers.amount) else 0 end) as asks from `archive_ledgers` inner join `accounts` on `archive_ledgers`.`account` = `accounts`.`account` inner join `orders` on `orders`.`id` = `archive_ledgers`.`order_id` where `accounts`.`account_type` <= ? and `archive_ledgers`.`account` >= ? and `document_date` <= ? and `document_date` >= ? group by `archive_ledgers`.`booking_type`, left(archive_ledgers.account,3) order by `archive_ledgers`.`booking_type` desc) s1 group by `s1`.`account`)