How can i do a nested select using Laravel raw query?
SELECT day_of_week, AVG(order_count) average_order FROM
(
SELECT DAYNAME(order_date) day_of_week,
DAYOFWEEK(order_date) day_num,
TO_DAYS(order_date) date,
count(*) order_count
FROM orders
GROUP BY date
) temp
GROUP BY day_of_week
ORDER BY day_num
This is what I tried so far:
DB::table('(
SELECT DAYNAME(order_date) day_of_week,
DAYOFWEEK(order_date) day_num,
TO_DAYS(order_date) date,
count(*) order_count
FROM orders
GROUP BY date
) temp')
->select(DB::raw('day_of_week, AVG(order_count) average_order'))
->groupBy(DB::raw('day_of_week'))
->orderBy(DB::raw('day_num'))
->get();
This is not working, but so far this query is very close.
By the way, I am using Laravel 5.6.
Thanks!