單個select語句實現(xiàn)MySQL查詢統(tǒng)計次數(shù)
作者:佚名
MySQL中查詢統(tǒng)計次數(shù)往往語句寫法很復雜,下文就教您一個只用單個select語句就實現(xiàn)的方法,希望對您能夠有所幫助。
單個select語句實現(xiàn)MySQL查詢統(tǒng)計次數(shù)的方法用處在哪里呢?用處太多了,比如一個成績單,你要查詢及格得人數(shù)與不及格的人數(shù),怎么一次查詢出來?
MySQL查詢統(tǒng)計次數(shù)簡單的語句肯定是這樣了:
- select a.name,count_neg,count_plus from
- (select count(id) as count_plus,name from score2 where score >=60 group by name) a,
- (select count(id) as count_neg,name from score2 where score <=60 group by name) b
- where a.name=b.name
即必須至少用2個語句。
今天剛好碰到發(fā)現(xiàn)mysql支持if,那就創(chuàng)造性的用if來實現(xiàn)吧:
- select name, sum(if(score>=60,1,0)),sum(if(score<60,1,0)) from score2 group by name
單個select語句實現(xiàn)MySQL查詢統(tǒng)計次數(shù)的方法簡單吧。
原理就是大于60,就賦值為1,那么sum就是計數(shù)了。
【編輯推薦】
責任編輯:段燃
來源:
百度空間