问题利用Mysql实现多个sum计算(mysql多个sum)
MySQL是当今比较流行的关系型数据库管理系统,它的功能强大,支持查询多个列的求和。但是如果要同时求多个列的和,很多人会比较疑惑,毕竟SQL语句有很多种写法,比较容易出错。今天就来介绍一种基于MySQL实现多个sum计算的简单方法。
首先,我们准备一个测试表格如下所示:
![img](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8dGl0bGU+dGFibGU8L3RpdGxlPgo8ZyBpZD0iTGF5ZXJfMSIgZGlzcGxheT0ibm9uZSI+CjxnIGlkPSJHcm91cF8yIj4KPHBhdGggaWQ9IlBhdGhfMSIgZD0iTTY1LjYzLDIzLjUxSDBGIE01My40OSw3Ljc3aDE2LjA2IiBzdHlsZT0iZmlsbDpub25lOyBzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MSIvPgo8L2c+CjxsaW5lIGlkPSJMaW5lXzQiIHgxPSI2OC4zMiIgeTE9IjIwLjI3IiB4Mj0iNjguMzIiIHkyPSIzNi4zNCIgc3R5bGU9ImZpbGw6bm9uZTtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MSIvPgo8bGluZSBpZD0iTGluZV81IiB4MT0iNTMuNDkiIHkxPSI3Ljc3IiB4Mj0iNTMuNDkiIHkyPSIyMy41MSIgc3R5bGU9ImZpbGw6bm9uZTtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MSIvPgo8bGluZSBpZD0iTGluZV82IiB4MT0iNTMuNDkiIHkxPSIyMy41MSIgeDI9Ijc5LjA5IiB5Mj0iMjMuNTEiIHN0eWxl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cjtmaWxsOiMwMDAwMDA7c3Ryb2tlOiMwMDAwMDAiPjEyPC90ZXh0Pgo8L2c+Cjwvc3ZnPgo=)
使用MySQL语句sum计算上面表格的要实现多个sum计算,按照如下SQL语句:
SELECT SUM(Field1),SUM(Field2),SUM(Field3),SUM(Field4) FROM TableName
之所以可以一次求得多个列的求和,是因为MySQL的select语句支持用英文逗号隔开,将所选择的字段名称通过英文逗号放在一起。