bernte
bernte

Reputation: 1184

Multiple SUM for row

I have another little question. I have a mysql-table

cat | item |  data |
100 |   0  |   10  |
102 |   1  |   3   |
101 |   1  |   1   |
100 |   0  |   40  |
100 |   1  |   20  |
102 |   0  |   3   |
101 |   1  |   2   |
100 |   0  |   30  |
102 |   1  |   3   |

james_bond helped me with this code:

SELECT  cat, SUM(IF(item = 0,1,0)) AS items0,  
    SUM(IF(item = 1,1,0)) AS items1 FROM table GROUP BY cat

I get the result:

categories |   items 0  |   items 1
100        |     3      |     1 
101        |     0      |     2 
102        |     1      |     2 

Now I need another rule to get the following result:

I want the sum of data for item 0 and item 1:

categories |   data 0  |   data 1
100        |     80    |     20 
101        |     0     |     3 
102        |     3     |     6

I would be happy if someone could help me.

Upvotes: 0

Views: 150

Answers (1)

Briguy37
Briguy37

Reputation: 8402

It should be a similar query:

SELECT 
  cat, 
  SUM(IF(item = 0,data,0)) AS data0,  
  SUM(IF(item = 1,data,0)) AS data1 
FROM table GROUP BY cat;

Upvotes: 3

Related Questions