4

I'm trying to simplify a set of queries into a single one an am struggling with it.

I want to collect counts of different ranges and am doing this right now:

select count(*) from items where value < 0 and id = 43;

select count(*) from items where (value >= 0 AND value <= 10) and id = 43;

select count(*) from items where (value > 10 AND value <= 20) and id = 43;

select count(*) from items where (value > 20 AND value <= 30) and id = 43;

select count(*) from items where value > 30 and id = 43;

I want to be able to do this in a single query. How can I accomplish that?

Also I need each individual queries count still, not just a total of them together.

0

2 Answers 2

5
SELECT
    SUM( IF(value < 0, 1, 0) ),
    SUM( IF(value BETWEEN 0 AND 10, 1, 0) ),
    SUM( IF(value BETWEEN 10 AND 20, 1, 0) ),
    SUM( IF(value BETWEEN 20 AND 30, 1, 0) ),
    SUM( IF(value > 30, 1, 0) )
FROM items
WHERE id = 43;

Give this a try

Sign up to request clarification or add additional context in comments.

Comments

4

Maybe something like this:

SELECT 
    SUM(CASE WHEN value < 0 and id = 43 THEN 1 ELSE 0 END) AS c1
    SUM(CASE WHEN (value >= 0 AND value <= 10) and id = 43 THEN 1 ELSE 0 END) AS c2,
    SUM(CASE WHEN (value > 10 AND value <= 20) and id = 43 THEN 1 ELSE 0 END) AS c3,
    SUM(CASE WHEN (value > 20 AND value <= 30) and id = 43 THEN 1 ELSE 0 END) AS c4,
    SUM(CASE WHEN value > 30 and id = 43 THEN 1 ELSE 0 END) AS c5
FROM 
    items

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.