6

Trying to get the sum of a int field in one of my table should be pretty easy, unfortunately it is not as I'm getting different result whether I use Laravel, MySQL or Excel.

Laravel 5.4 gives me 20506:

Table::sum('field_name');

MySQL gives me 1830:

Select sum(field_name) from table;

And the data from the Excel sheet before importing it into the database: Sum gives me 145689

Any idea? I tried to cast to integer before doing the sum but it doesn't work. All the numbers are pretty big but don't contain comma or dot.

Examples of values I have to sum: (contain sometimes empty cells)

17906774
99630157
28581131

159551532
20312892
668928885
1
  • What do you get if you do a foreach sum of all rows in laravel? Commented Nov 2, 2017 at 13:16

3 Answers 3

5
$query = YourModel::query();
$query->withCount([
'activity AS yoursum' => function ($query) {
        $query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid');
    }
]);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.
I agree with Toby and I can see after many years no explanation has been added. That's why I'm downvoting.
5

You can use laravel aggregate function SUM as :

$result = DB::table('table_name')
                ->select(DB::raw('SUM(field_name) as total_field_name'))
                ->get();

For more details you can follow:

https://laravel.com/docs/5.4/queries

Thanks

1 Comment

It unfortunately doesn't change the result.
1

Try with

$result = DB::table(tablename)
->selectRaw('sum(column)')
->get();

If it still gives you wrong result, maybe wait for someone to give you a better answer. This is all I could think of.

1 Comment

This gives me the same result as the SQL query: Select sum(field_name) from table;

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.