根据 SQL 中的条件计数

Count based on a Conditions in SQL

我想统计关卡

输入

|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 的级别的计数。但是如何在一个实例中获取所有这些?

如果您希望每个范围有 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

我会构建一个 table 范围并加入它

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

最有效的方法应该是用累加和聚合:

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;