需求背景:有个报表需要根据凭证表汇总数据,但是因为凭证表的数据量比较大,我们把凭证表分表了
现在需要根据条件把数据查询出来之后根据科目再汇总
voucher2021,voucher2022,voucher2023 三张样表
$query = DB::table('voucher2021')
->select(['subject_code'])
->selectRaw('SUM(borrow_account) as borrow_sum')
->selectRaw('SUM(credit_account) as credit_sum')
->selectRaw("DATE_FORMAT(input_date, '%Y-%m') as gen_date")
->where('input_date', '>=', $startDate)
->where('input_date', '<=', $endDate)
->groupBy(['subject_code', DB::raw("DATE_FORMAT(input_date, '%Y-%m')")]);
$query1 = DB::table('voucher2022')
->select(['subject_code'])
->selectRaw('SUM(borrow_account) as borrow_sum')
->selectRaw('SUM(credit_account) as credit_sum')
->selectRaw("DATE_FORMAT(input_date, '%Y-%m') as gen_date")
->where('input_date', '>=', $startDate)
->where('input_date', '<=', $endDate)
->groupBy(['subject_code', DB::raw("DATE_FORMAT(input_date, '%Y-%m')")]);
$query2 = DB::table('voucher2023')
->select(['subject_code'])
->selectRaw('SUM(borrow_account) as borrow_sum')
->selectRaw('SUM(credit_account) as credit_sum')
->selectRaw("DATE_FORMAT(input_date, '%Y-%m') as gen_date")
->where('input_date', '>=', $startDate)
->where('input_date', '<=', $endDate)
->groupBy(['subject_code', DB::raw("DATE_FORMAT(input_date, '%Y-%m')")]);
$unionAllQuery = $query->unionAll($query1)->unionAll($query2);
// 注意这里 之前网上大部分都是 DB::table(DB::raw("({$unionAllQuery->toSql()}) as sub"))->mergeBindings($unionAllQuery->getQuery())
// 这种写法也是可以得到结果的,但是这种方法不提倡,如果你的项目有psalm的钩子,你的代码是不能通过的
// 因为 DB::table 需要的参数Builder 或者 string
$result = DB::table($unionAllQuery, "sub")
->selectRaw('sub.subject_code as subject_code')
->selectRaw('SUM(sub.borrow_sum) as borrow_sum')
->selectRaw('SUM(sub.credit_sum) as credit_sum')
->selectRaw('sub.gen_date as gen_date')
->groupBy(['sub.subject_code', 'sub.gen_date'])
->get();