Abdul Jabbar
Abdul Jabbar

Reputation: 5931

Calculate sum of Single column on the Basis of another column in MySQL

I want to get two(2) different SUM of Single Column "Amount" on the Basis of "Type" Column.

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           |
+-------------+-------------+-------------+

Means to say that in above example there is Type column which only have 0 or 1 and I want to get sum of "Amount" column group by "CustID".

Upvotes: 0

Views: 139

Answers (2)

tanaydin
tanaydin

Reputation: 5306

seems that is the query you are looking for.

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

Upvotes: 1

Mihai
Mihai

Reputation: 26784

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

Upvotes: 1

Related Questions