【问题标题】:Count based on a Conditions in SQL根据 SQL 中的条件进行计数
【发布时间】:2021-08-30 19:03:13
【问题描述】:

我想计算等级

输入

|id|levels|
|--| --- |
|1 |9    |
|2 |12   |
|3 |21   |
|4 |23   |
|5 |11   |
|6 |31   |
|7 |23   |
|8 |11   |
|9 |31   |

预期输出

|range        |count|
|-------------|-----|
|more than 10 | 8   |
|more than 20 | 5   |
|more than 30 | 2   |

目前,我正在单独编写查询以获取大于 10、20 和 30 的计数。但是如何在一个实例中获取它们?

【问题讨论】:

  • 定义不正确,因为我们无法猜测您在数什么,正如发布指南所建议的那样,显示您为尝试解决您的问题所做的工作可能会有所帮助
  • 接受的答案与预期的输出不匹配。

标签: mysql sql count union


【解决方案1】:

最有效的方法应该是累积总和:

select (case when levels > 10 then 'more than 10'
             when levels > 20 then 'more than 20'
             when levels > 30 then 'more than 30'
        end) as range,
       sum(count(*)) over (order by min(levels)) as count
from t
where levels > 10
group by range;

【讨论】:

    【解决方案2】:

    如果您希望每个范围有 1 行,则使用 3 个不同的查询和 UNION ALL 以获得最终结果:

    SELECT 'more than 10' AS `range`, COUNT(*) AS count FROM tablename WHERE levels > 10
    UNION ALL
    SELECT 'more than 20' AS `range`, COUNT(*) AS count FROM tablename WHERE levels > 20
    UNION ALL
    SELECT 'more than 30' AS `range`, COUNT(*) AS count FROM tablename WHERE levels > 30
    

    使用条件聚合获得 1 行 3 列的结果会更容易:

    SELECT SUM(levels > 10) AS `more than 10`, 
           SUM(levels > 20) AS `more than 20`,
           SUM(levels > 30) AS `more than 30`
    FROM tablename 
    

    请参阅demo

    【讨论】:

      【解决方案3】:

      我会建立一个范围表并加入它

      SELECT CONCAT('greater than ', n) AS range, COUNT(*) AS c
      FROM (
      SELECT 10 AS n UNION ALL
      SELECT 20 AS n UNION ALL
      SELECT 30 AS n
      ) AS r
      INNER JOIN your_table ON level >= n
      GROUP BY n
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-07
        相关资源
        最近更新 更多