MySQL中查询统计次数往往语句写法很复杂,下文就教您一个只用单个select语句就实现的方法,希望对您能够有所帮助。

 

 

单个select语句实现MySQL查询统计次数的方法用处在哪里呢?用处太多了,比如一个成绩单,你要查询及格得人数与不及格的人数,怎么一次查询出来?

MySQL查询统计次数简单的语句肯定是这样了:

  1. select a.name,count_neg,count_plus from
  2. (select count(id) as count_plus,name from score2 where score >=60 group by name) a,
  3. (select count(id) as count_neg,name from score2 where score <=60 group by name) b
  4. where a.name=b.name

即必须至少用2个语句。

今天刚好碰到发现mysql支持if,那就创造性的用if来实现吧:

  1. select name, sum(if(score>=60,1,0)),sum(if(score<60,1,0)) from score2 group by name

单个select语句实现MySQL查询统计次数的方法简单吧。

原理就是大于60,就赋值为1,那么sum就是计数了。

相关文章:

  • 2022-12-23
  • 2021-08-09
  • 2021-09-07
  • 2021-07-04
  • 2022-12-23
  • 2021-11-07
  • 2022-01-13
  • 2022-12-23
猜你喜欢
  • 2021-05-17
  • 2021-12-05
  • 2021-05-07
  • 2021-12-22
  • 2021-12-05
  • 2021-10-02
相关资源
相似解决方案