Mysql 使用 case when 语句进行计数

标签 mysql

考虑:

SELECT(count(c.id),
    case when(count(c.id) = 0)
             then 'loser'
         when(count(c.id) BETWEEN 1 AND 4)
             then 'almostaloser'
         when(count(c.id) >= 5)
             then 'notaloser'
    end as status,
   ...

当一切都说完并完成后,查询作为一个整体会产生一组与此类似的结果:

   Count  | status
  --------|-------------
     2    | almostaloser   //total count is between 2 and 4
  --------|-------------
     0    | loser          // loser because total count = 0
  --------|-------------
     3    | almostaloser  //again, total count between 2 and 4
  --------|-------------

我想要实现的目标:

一种重新保留上表中信息的方法,但添加第三列,该列将给出每个状态的总数,类似于

   select count(c.id)
     case when(count(c.id) = 0 )
        then loser as status AND count how many  of the total count does this apply to

结果类似于:

   Count  | status      |total_of each status |
  --------|-------------|---------------------|
     2    | almostaloser|   2                 |   
  --------|-------------|---------------------|
     0    | loser       |   1                 |  
  --------|-------------|---------------------|
     3    | almostaloser|   2                 |
  --------|-------------|----------------------

我被告知这可以使用派生表来实现,但我还无法同时获得它们,只能获得其中之一。

最佳答案

这可以通过此查询来实现(您必须将原始查询作为子查询放置在两个位置):

SELECT t1.*, t2.total_of_each_status
  FROM (
    -- put here your query --
  ) t1
  INNER JOIN (
    SELECT status, count(*) AS total_of_each_status
      FROM (
        -- put here your query --
      ) t2
      GROUP BY status
  ) t2 ON t2.status = t1.status

关于Mysql 使用 case when 语句进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26618368/

相关文章:

php - 为什么这没有提取任何数据?

python - NLP项目数据库

mysql - 如何查询 OLAP 多维数据集中的数据(不使用 Excel)

更改表添加主键时 PHP 返回错误

php - 在大型 Mysql 数据库中搜索行 ID 中的确切日期

php - 尽管通过 mysql 中的 select 语句进行验证,但有时会产生重复记录

MySQL 表无法读取

php - 只有一个 MySQL 查询的两个 foreach 语句?

php - 如何在MySQL中使用两个标签参数过滤结果?

php - 使用PHP中的下拉菜单删除数据库中的数据