在一个表中对多个字段求和


Sum multiple fields in 1 table

你好,我想在我的表中汇总我的4列。但我得到了错误he SUM function requires 1 argument(s)itemcost表

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

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

提前感谢。

对每一行的列进行求和,使用:

(col1+col2+col3+col4) as unitprice

或者,将列与行相加,使用:

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

顺便说一下,这里有一篇带有示例的文章

你可以用+号添加列,试试下面的命令:

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