COUNT
NULL以外の数をカウントする
全ての値をカウントする場合→ count(*)
特定のフィールドをカウントする→ count(field)
select count(*) as total, block, tantou, count(if(keiyaku=’契約’,’1′,NULL)) as keiyakusu from mitumori GROUP BY tantou ORDER BY total desc
このsqlの解説
- mitumoriテーブルをtantouでグループわけして集計する
- count(*) as total
グループごとの数を数え、変数totalに代入 - count(if(keiyaku=’契約’,’1′,NULL)) as keiyaku
keiyakuの値が契約の場合、1を代入しそれ以外はNULLを代入する。その数をcountし、変数keiyakusuに代入する - ORDER BY total desc
集計数の多い順にソートする。