mercredi 26 octobre 2016

MySQL SELECT IF differentiate SUM

My database structure looks as follows:

id    |    valuefor   |    quantity
1          alpha           500
2          alpha           100
3          beta            200

I am using following mysql command

SELECT IF(valuefor=alpha, SUM(quantity),0) as alpha, IF(valuefor=beta, SUM(quantity),0) as beta FROM mytable

Current Output:

alpha   |   beta
800         0

The obvious issue with the above is that it SUMS all the rows since I have used SUM. How can I overcome this dilemma? I want to get quantity of alpha and beta separately.

Secondly I am confused as to why did the beta not have value=800 in the output and why does it say 0. This is just for my better understanding of the issue.

I want to result to look something as follows:

alpha    |    beta
600           200

Aucun commentaire:

Enregistrer un commentaire