I would like to calculate every item's vote count for this table:
user item vote
--------------------------------
4 1 left
4 2 left
2 2 right
3 2 left
1 3 right
The result must be like this:
item | left_vote | right_vote
1 1 0
2 2 1
3 0 1
I've tried to use queries like this:
SELECT t.item, count(vote) as left_count, t.right_count from (SELECT count(vote) as right_count, item from view where vote = 'right') as t, view where vote = 'left';
But it doesn't work. I think that I have to use join with subquery.
Is it real with mysql?
In MySQL you can just use conditional aggregation:
select item, sum(vote = 'left') as left_vote, sum(vote = 'right') as right_vote
from votes v
group by item;
You don't need a join or subquery for this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.