用于加权投票的MySQL查询 - 如何使用分配给不同列的值进行计算

时间:2013-01-08 14:47:29

标签: mysql

我有一个投票应用程序,它将值写入mysql数据库表。这是一个偏好/加权投票系统,因此人们选择第一个选项,第二个选项和第三个选项。这些都进入表中的单独字段。我正在寻找一种方法来编写一个查询,该查询将为响应分配数值(第一个响应为3,第二个响应为2,第一个响应为1),然后使用总计得分显示该值。我已经能够以总票数

来做到这一点
select count(name) as votes,name 
from (select 1st_option as name from votes 
      union all 
      select 2nd_option from votes 
      union all 
      select 3rd_option from votes) as tbl 
group by name 
having count(name) > 0 
order by 1 desc;

但还没有弄清楚如何为每个列中的响应赋值,然后将它们拉到一起。任何帮助深表感谢。谢谢!

1 个答案:

答案 0 :(得分:3)

你可以这样做:

select sum(score) as votes,name 
from (select 1st_option as name, 3 as score from votes 
      union all 
      select 2nd_option as name, 2 as score from votes 
      union all 
      select 3rd_option as name, 1 as score from votes) as tbl 
group by name;