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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With