在MySQL中选择两个柱状和?

Rea*_*ues 0 mysql sql

我可以使用SUM()MySQL中的函数轻松选择一列的总和,如下所示:

SELECT SUM(`someColumn`) FROM `table`
Run Code Online (Sandbox Code Playgroud)

是否也可以使用相同的查询返回第二列的总和?与此类似:

SELECT SUM (`someColumn`, `anotherColumn`) FROM `table`
Run Code Online (Sandbox Code Playgroud)

运行此类查询会返回以下访问冲突:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' `anotherColumn`) FROM `table`' at line 1
Run Code Online (Sandbox Code Playgroud)

Mil*_*len 5

试试:

SELECT SUM(COALESCE(`someColumn`, 0)+ COALESCE(`anotherColumn`, 0)) as TotalSum FROM `table`
Run Code Online (Sandbox Code Playgroud)

或者如果你想分开这些:

SELECT SUM(`someColumn`) as Sum1, SUM(`anotherColumn`) as Sum2 FROM `table`
Run Code Online (Sandbox Code Playgroud)