0

I am trying to convert the following query to laravels using query builder but having some issue with group by clause and sum aggregated functions

SELECT code, SUM(quantity) as quantity, SUM(sale_price) as price
FROM `orders` o
GROUP By code

I have tried this, this is what I have after so many desperate tries.

$args['orders'] = DB::table('orders')
->havingRaw('sum(sale_price)')
->havingRaw('code')
->where([ 'shop_id' => $shop_id ])
->groupBy('code')
->get();

1 Answer 1

1

Try with

$args['orders'] = DB::table('orders')
->where('shop_id', '=', $shop_id)
->select('code', DB::raw('sum(quantity) as quantity, sum(sale_price) as price'))
->groupBy('code')
->get();

Order by

$args['orders'] = DB::table('orders')
->where('shop_id', '=', $shop_id)
->select('code', DB::raw('sum(quantity) as quantity, sum(sale_price) as price'))
->groupBy('code')
->orderBy('quantity')
->get();

Or try

->orderByRaw('sum(quantity)')
Sign up to request clarification or add additional context in comments.

8 Comments

How would I add order_by column in this?
Nah, order_by is actually a column which will be joined to another table.
Then simply use tablename.column inside of orderBy()
SELECT code, order_by, SUM(quantity) as quantity, SUM(sale_price) as price FROM orders o GROUP By code
Then simply add ->orderBy('order_by') to the query before get()
|

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.