Допустим, у нас есть таблица billings
, например:
| column | type |
|------------|------------|
| id | int |
| store | varchar |
| amount | int |
| created_at | timestamps |
| updated_at | timestamps |
Я получу количество каждого магазина в current_day
, current_month
, current_week
, current_year
и overall
с помощью подзапроса, подобного этому:
select
store,
(SELECT SUM(amount) from billings as child where child.store = parent.store and DAY(created_at) = ? and MONTH(created_at) = ? and YEAR(created_at) = ?) as current_day,
(SELECT SUM(amount) from billings as child where child.store = parent.store and WEEK(created_at) = ?) as current_week,
(SELECT SUM(amount) from billings as child where child.store = parent.store and MONTH(created_at) = ? and YEAR(created_at) = ?) as current_month,
(SELECT SUM(amount) from billings as child where child.store = parent.store and YEAR(created_at) = ?) as current_year,
SUM(amount) as overall,
COUNT(id) as total_rows
from billings as parent
group by store
А с Eloquent
это будет примерно так:
$childQuery = \DB::table(\DB::raw('billings as child'))
->select(\DB::raw('SUM(amount) as amount'))
->whereRaw('child.store = parent.store');
$currentDayQuery = (clone $childQuery)->whereDay('created_at', now()->day)->whereMonth('created_at', now()->month)->whereYear('created_at', now()->year);
$currentWeekQuery = (clone $childQuery)->where(\DB::raw('WEEK(created_at)'), now()->weekOfYear);
$currentMonthQuery = (clone $childQuery)->whereMonth('created_at', now()->month);
$currentYearQuery = (clone $childQuery)->whereYear('created_at', now()->year);
$rows = \DB::table(\DB::raw('billings as parent'))
->select([
'store',
\DB::raw('(' . $currentDayQuery->toSql() . ') as current_day'),
\DB::raw('(' . $currentWeekQuery->toSql() . ') as current_week'),
\DB::raw('(' . $currentMonthQuery->toSql() . ') as current_month'),
\DB::raw('(' . $currentYearQuery->toSql() . ') as current_year'),
\DB::raw('SUM(amount) as overall'),
\DB::raw('COUNT(id) as total_rows')
])
->mergeBindings($currentDayQuery)
->mergeBindings($currentWeekQuery)
->mergeBindings($currentMonthQuery)
->mergeBindings($currentYearQuery)
->groupBy('store')
->get();
Надеюсь, это поможет.