简体   繁体   English

mysql | 分组和计数行

[英]mysql | Group and count rows

I have a table and would like to calculate values. 我有一张桌子,想计算值。 My table: 我的桌子:

Table votes 表票

vote   type
1      1
-1     1
1      0
-1     0
1      0
-1     1
1      0

Vote: -1 - Down; 投票:-1-下调; +1 - Up; +1-向上;

I would like to get something like this: 我想得到这样的东西:

Count votes up type 1: 1
Count votes down type 1: 2

Votes up type 0: 3
Votes down type 0: 1

Sum votes type 1: 1+(-1)+(-1) = -1
Sum votes type 0: 1+(-1)+1+1 = 2

Is it possible to get results from mysql using single query? 是否可以使用单个查询从mysql获取结果? Thanks! 谢谢!

I guess your problem is how to distinct up and down votes here. 我想您的问题是如何在此处区分上下投票。

You want to group by type (which sounds like a vote/poll ID) and then just pick up and down votes. 您想按类型分组(听起来像是投票/投票ID),然后只进行上下投票。 It can be done using CASE or IF in combination with COUNT or SUM . 可以使用CASEIF结合COUNTSUM

COUNT does not count NULL values so I suggest to wrap two COUNT s in IF s. COUNT不计算NULL值,因此我建议在IF包装两个COUNT

SELECT
type,
COUNT(IF(vote = -1, TRUE, NULL)) AS down,
COUNT(IF(vote = 1, TRUE, NULL)) AS up
FROM votes
GROUP BY type

SQL Fiddle: http://sqlfiddle.com/#!2/36008/1/0 SQL小提琴: http ://sqlfiddle.com/#! 2/36008/1/0

you can write 你可以写

select count(*) from table where type = 1 and vote = -1


select count(*) from table where type = 1 and vote = 1

the above will give you the result count which you want . 以上将为您提供所需的结果计数。

这会工作

  select sum(vote),type from table group by type;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM