0

我想在“类型”列的基础上获得两(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”列组的总和。

4

2 回答 2

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
于 2013-10-21T20:54:43.347 回答
1

似乎这就是您要查找的查询。

SELECT
    CustID,
    SUM(IF(type=0,amount,0)) as amount1,
    SUM(IF(type=1,amount,0)) as amount2
FROM
    tbl
GROUP BY
    CustID;
于 2013-10-21T20:54:51.983 回答