0

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!

3
  • Have you tried anything? What's your Laravel version? Commented Jul 30, 2018 at 11:07
  • @JonasStaudenmeir i've updated my question with the query that I tried. I am using Laravel 5.6. Commented Jul 30, 2018 at 11:10
  • there is method in laravel of using raw query did you try that @PinoyStackOverflower Commented Jul 30, 2018 at 12:45

2 Answers 2

2

Use DB::raw() in table() and don't use it in groupBy() and orderBy():

DB::table(DB::raw('(
      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('day_of_week', DB::raw('AVG(order_count) average_order'))
    ->groupBy('day_of_week')
    ->orderBy('day_num')
    ->get();

You can also use fromSub():

$from = DB::table('orders')
    ->selectRaw(
        'DAYNAME(order_date) day_of_week,
        DAYOFWEEK(order_date) day_num, 
        TO_DAYS(order_date) date,
        count(*) order_count'
    )->groupBy('date');
DB::query()->fromSub($from, 'temp')
    ->select('day_of_week', DB::raw('AVG(order_count) average_order'))
    ->groupBy('day_of_week')
    ->orderBy('day_num')
    ->get();
Sign up to request clarification or add additional context in comments.

1 Comment

I wasn't aware I can use DB::raw in the table. Thanks much for this! You are a savior!
0

Try This , but surely it's need to edit

DB::table('orders')
    ->select(DB::raw('(SELECT order_date AS day_of_week, order_date AS day_num, order_date AS date FROM orders GROUP BY date)'))
    ->groupBy(DB::raw('day_of_week'))
    ->orderBy(DB::raw('day_num'))
    ->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.