Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL sum based on col value

Tags:

sql

mysql

I have this table:

+----+--------+-------+
| id | fruit  | a-b-c |
+----+--------+-------+
| 1  | orange | a     |
+----+--------+-------+
| 2  | banana | c     |
+----+--------+-------+
| 3  | orange | c     |
+----+--------+-------+
| 4  | orange | a     |
+----+--------+-------+
| 5  | orange | b     |
+----+--------+-------+

Now I want to list all the fruits and a sum based on the a-b-c values.a=1, b=2 and c=3. So, this would be the result I want:

+--------+-----+
| fruit  | sum |
+--------+-----+
| banana | 3   |
+--------+-----+
| orange | 7   |
+--------+-----+

I'm fairly sure that I should use case, but I have no idea how to sum them. I have something like this in my mind:

SELECT
    fruit,
    sum(a-b-c)
    CASE
        WHEN a-b-c = 'a' THEN +=1
        ELSE
    CASE
        WHEN a-b-c= 'b' THEN +=2
        ELSE
    CASE
        WHEN a-b-c= 'c' THEN +=3

    END AS sum

FROM tbl_fruits
GROUP BY fruit;
like image 848
fishmong3r Avatar asked May 02 '16 06:05

fishmong3r


1 Answers

You could use conditional aggregation:

SELECT fruit, SUM(CASE `a-b-c`
                     WHEN 'a' THEN 1
                     WHEN 'b' THEN 2
                     WHEN 'c' THEN 3
                  END) AS total 
FROM tbl_fruits
GROUP BY fruit;

SqlFiddleDemo

Output:

╔═════════╦═══════╗
║ fruit   ║ total ║
╠═════════╬═══════╣
║ banana  ║     3 ║
║ orange  ║     7 ║
╚═════════╩═══════╝

Alternatively using ELT/FIELD:

SELECT fruit, SUM(ELT(FIELD(`a-b-c`,'a','b','c'),1,2,3)) AS total 
FROM tbl_fruits
GROUP BY fruit;

SqlFiddleDemo2

like image 58
Lukasz Szozda Avatar answered Sep 29 '22 18:09

Lukasz Szozda