0

These are given data

No CompanyName Price
 1     A       $2.5
 2     B       $5.1
 3     C       $10
 4     A       $1.3
 5     A       $5.1
 6     B       $2.5
 7     B       $2.3
 8     C       $2.3

Expecting Result
Company  Price
  A        $2.5 + $1.3 + $5.1
  B        $5.1 + $2.5 + $2.3
  C        $10 + $2.3

How can I get this result using laravel eloquent

Qingri
  • 23
  • 3
  • Does this answer your question? [Laravel Eloquent: sum with groupBy](https://stackoverflow.com/questions/24887708/laravel-eloquent-sum-with-groupby) – ManojKiran A Dec 23 '21 at 03:33

3 Answers3

1
ModelName::groupBy('CompanyName')
   ->selectRaw('*, sum(Price) as sum')
   ->get();
0

I am note sure if I got your question right, but I think you want the sum of all columns where the company name is for example A

You can get it this way:

DB::table('your_table')->where('CompanyName', '=', 'desired_name')->sum(price);

So you put in the name of your table in 'your_table' - then you pick those out where the CompanyNamematches the company you are looking for (desired_name') and calculate the sumof price

desertnaut
  • 57,590
  • 26
  • 140
  • 166
newbie
  • 525
  • 2
  • 12
  • If follow your way, I don't get result with only one command. I want to get result without "desired_name". I want to get sum of records according to all company, Any other way? – Qingri Dec 22 '21 at 17:48
  • @Qingri you can make a separate query for each company and replace desired_name with the name of the company. – newbie Dec 22 '21 at 17:49
0

You can use groupBy.

Model::query()->select('company_name', DB::raw('SUM(price) as total_price'))->groupBy('company_name')->get();

And if you want to add conditions to this result, you can use having like this:

Model::query()->select('company_name', DB::raw('SUM(price) as total_price'))->groupBy('company_name')->having('total_price', '>', 100)->get();
desertnaut
  • 57,590
  • 26
  • 140
  • 166
baleghsefat
  • 192
  • 3
  • 9