1

I have this table

create table votes(
    candidate varchar(20),
    voteup bool
)

and I want to display something like this

|candidate|vote ups(true)|vote downs(false)|vote points(true-false)
|hitler   |16            |104              |-88
|obama    |119           |1                |118
user1625766
  • 151
  • 9

2 Answers2

3

You can "abuse" the fact that boolean values evaluate as 1 and 0 in integer operations:

select candidate,
    sum(voteup) as 'vote up',
    sum(voteup=0) as 'vote down',
    sum(if(voteup,1,-1)) as 'vote points'
from votes
group by candidate;
Timothée Groleau
  • 1,940
  • 13
  • 16
0
SELECT candidate, 
       SUM(IF(voteup=0,0,1)) 'vote ups (true)',
       SUM(IF(voteup=0,1,0)) 'vote downs (false)',
       SUM(IF(voteup,1,-1)) 'vote points (true-false)'
FROM votes
GROUP BY candidate

I changed my original answer because BOOL / TINYINT(1) can contain any number between -128 and 127

Mario
  • 196
  • 1
  • 8