Mysql count occurrence by group(Mysql 按组计数出现次数)

本文介绍了Mysql 按组计数出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 mysql 数据库上有下表.

Hi i have following table on mysql DB.

╔═══════════╦═════════╦════════╦════════════════╗
║ REVIEW_ID ║ USER_ID ║ STATUS ║   DATE_ADDED   ║
╠═══════════╬═════════╬════════╬════════════════╣
║       218 ║       2 ║ cool   ║ 20130121134811 ║
║       218 ║       2 ║ cool   ║ 20130121134812 ║
║       218 ║       2 ║ lame   ║ 20130121134813 ║
║       218 ║       2 ║ funny  ║ 20130121134814 ║
║       218 ║       2 ║ funny  ║ 20130121134815 ║
║       218 ║       2 ║ funny  ║ 20130121134816 ║
║       218 ║       2 ║ lame   ║ 20130121134817 ║
╚═══════════╩═════════╩════════╩════════════════╝

如何获得结果,当我根据 user_id 进行查询时,我需要获得每种类型的总状态结果:

how can i get a result where when i do query based on user_id i need to get result of total status for each type:

╔════════╦════════════╗
║ STATUS ║ TOTALCOUNT ║
╠════════╬════════════╣
║ cool   ║          2 ║
║ funny  ║          3 ║
║ lame   ║          2 ║
╚════════╩════════════╝

谢谢

推荐答案

使用COUNT()是一个聚合函数,根据状态进行分组>

Use COUNT() which is an aggregate function, and group them according to their status

SELECT  status, COUNT(*) totalCount
FROM    tableName
GROUP   BY status

  • SQLFiddle 演示
  • 其他

    • MySQL GROUP BY 和一些聚合函数列表

    这篇关于Mysql 按组计数出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!