在MySQL的另一列的基础上计算单列的总和

时间:2013-10-21 20:46:00

标签: mysql sum

我希望在“类型”列的基础上得到两(2)个不同的单列“金额”。

mysql>select * from tbl;
+--------+----------+----------+----------+
|   id   |  CustID  |  amount  |   type   |
+--------+----------+----------+----------+
|      1 | 1        | 100      | 0        |
|      2 | 2        | 200      | 0        |
|      3 | 3        | 200      | 0        |
|      4 | 1        | 100      | 1        |
|      5 | 1        | 100      | 0        |
|      4 | 3        | 100      | 0        |
|      5 | 1        | 300      | 1        |
|      6 | 2        | 100      | 1        |
+--------+----------+----------+----------+


mysql>Query Result (Want this Result);
+-------------+-------------+-------------+
|    CustID   |   amount1   |   amount2   |
+-------------+-------------+-------------+
| 1           | 200         | 400         |
| 2           | 200         | 100         |
| 3           | 400         | 0           |
+-------------+-------------+-------------+

意思是说在上面的例子中有Type列只有0或1而我想通过“CustID”得到“Amount”列组的总和。

2 个答案:

答案 0 :(得分:1)

SELECT CustID,SUM(CASE WHEN `type` =0 THEN amount ELSE 0 END) AS amount1,
              SUM(CASE WHEN `type` =1 THEN amount ELSE 0 END) AS amount2
FROM tableName GROUP BY CustID

答案 1 :(得分:1)

似乎是您正在寻找的查询。

SELECT
    CustID,
    SUM(IF(type=0,amount,0)) as amount1,
    SUM(IF(type=1,amount,0)) as amount2
FROM
    tbl
GROUP BY
    CustID;