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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With