在MySQL中选择两个柱状和?

时间:2013-12-23 08:30:18

标签: mysql sql

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

SELECT SUM(`someColumn`) FROM `table`

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

SELECT SUM (`someColumn`, `anotherColumn`) FROM `table`

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

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

4 个答案:

答案 0 :(得分:5)

尝试:

SELECT SUM(COALESCE(`someColumn`, 0)+ COALESCE(`anotherColumn`, 0)) as TotalSum FROM `table`

或者如果你想分开这些:

SELECT SUM(`someColumn`) as Sum1, SUM(`anotherColumn`) as Sum2 FROM `table`

答案 1 :(得分:4)

SELECT SUM(`someColumn`) + SUM(`anotherColumn`) as TotalSum FROM `table`

答案 2 :(得分:0)

一种更简单的方法:

SELECT col1, col2, col3, (col1+col2+col3) AS Total FROM table;

答案 3 :(得分:0)

如果要对多个列求和,只需选择多个列的总和即可。

如果您只想要总列数,可以执行以下操作:

SELECT SUM(col1+col2+...+coln) AS all_total

如果您想将总和分开,您可以这样做:

SELECT SUM(col1) AS total1, SUM(col2) AS total2, ..., SUM(coln) AS totaln