开发者

Group by Row/Column Issue in MySQL

开发者 https://www.devze.com 2023-02-12 08:30 出处:网络
I\'m trying to get a series of counts of rows based upon a GROUP BY for a column. What I\'ve got at the moment is this:

I'm trying to get a series of counts of rows based upon a GROUP BY for a column. What I've got at the moment is this:

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;

What I imagined I would get would be something like:

Grouping_column | Count_A | Count_B

With Count_A and Count_B split by each level of grouping_column. However, this doesn't happen. Instead, what I get is the levels of the grouping_column listed, along with a count of ALL values that fall within the range specifi开发者_StackOverflow社区ed by Count_A and Count_B.

I've tried a number of different versions of this, but seem to be off the mark each time. What is it I'm doing wrong?


Try this:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消