简体   繁体   English

MySQL查询,多列求和

[英]MySQL query, SUM of multiple columns

I have multiple columns in a mySQL table. 我的mySQL表中有多个列。 Three of the columns are named i100s, i60s and i25s and what I want to do is get the sum of all three entries . 其中三列分别命名为i100s,i60s和i25s,而我想做的就是获取所有三个条目的总和。 currently I have this code 目前我有这个代码

   '$query= "SELECT SUM(i100s),SUM(i60s),SUM(i25s) AS tkit FROM event WHERE acc='100' " ; 
    $result = mysql_query($query) or die(mysql_error());
    $row = mysql_fetch_assoc($result) ;
    $total =  $row['tkit'];' 

But it is not returning the correct result. 但是它没有返回正确的结果。

Combined sum of all three columns? 所有三列的总和?

If so, simply add them up: 如果是这样,只需将它们加起来即可:

'$query= "SELECT SUM(i100s) + SUM(i60s) + SUM(i25s) AS tkit FROM event WHERE acc='100' " ;
SELECT (SUM(i100s) + SUM(i60s) + SUM(i25s)) AS tkit ...

这将返回列总和。

There will be different methods.... and the payments are payed on method_1, method_2, method_3. 会有不同的方法...。付款方式分别为method_1,method_2,method_3。 So I want to calculate the sum of one particular method say 1000.. for all method types. 因此,我想为所有方法类型计算一种特定方法的总和,例如1000..。

Table: payment_test 表格:payment_test

id method_1 payment_1 method_2 payment_2 method_3 payment_3
1  1000     100       1001     200       1001     100
2  1011     100       1000     100       1000     100
3  1010     200       1001     100       1010     200
4  1000     400       1010     500       1001     100


SELECT SUM(
    CASE WHEN method_1 ='1000' THEN payment_1 ELSE 0 END
    + CASE WHEN method_2 ='1000' THEN payment_2 ELSE 0 END
    + CASE WHEN method_3 ='1000' THEN payment_3 ELSE 0 END) as payment
FROM payment_test

Output: 输出:

payment 付款
700 700

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM