php - Sum multiple fields in 1 table

438

Hi I would like to sum my 4 columns in my table. but I get errorhe SUM function requires 1 argument(s) itemcost table

+------+------+------+------+------+
| id   | col1 | col2 | col3 | col4 |
+======+======+======+======+======+
| 0002 | 5    | 5    | 5    | 5    |
+------+------+------+------+------+
|      |      |      |      |      |
+------+------+------+------+------+
|      |      |      |      |      |
+------+------+------+------+------+


$cost= DB::table('itemcost')
            ->select(
                DB::raw('SUM(col1,col2,col3,col4) as unitprice')
            );

Thank you in advance.

155

Answer

Solution:

To sum just column of every single row, use:

(col1+col2+col3+col4) as unitprice

Or, to sum columns with rows, use:

(SUM(col1)+SUM(col2)+SUM(col3)+SUM(col4)) as unitprice

By the way, here is an article with examples

298

Answer

Solution:

You could add columns with + sign, Try like bellow:

      $cost= DB::table('itemcost')  
        ->select(
            DB::raw('SUM(col1+col2+col3+col4) as unitprice')
        );

People are also looking for solutions to the problem: php - Codeigniter - Failing to load config

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.