MySQL中的行/列问题分组

时间:2011-02-20 14:45:31

标签: mysql

我正在尝试根据列的GROUP BY获取一系列行数。我现在得到的是:

select grouping_column,
(select count(value) from table where value IS NOT NULL and value BETWEEN 0 AND 300) AS Count_A,
(select count(value) from table where value IS NOT NULL and value BETWEEN 301 AND 600) AS Count_B,
...many more like this...
from table
group by grouping_column;

我想象的就是:

Grouping_column | Count_A | Count_B

将Count_A和Count_B按每个grouping_column级别拆分。但是,这不会发生。相反,我得到的是列出的grouping_column的级别,以及Count_A和Count_B指定范围内的所有值的计数。

我尝试了很多不同的版本,但似乎每次都不合适。我做错了什么?

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT
    grouping_column,
    SUM(value BETWEEN 0 AND 300) AS Count_A,
    SUM(value BETWEEN 301 AND 600) AS Count_B,
    ...many more like this...
FROM yourtable
GROUP BY grouping_column