Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL query with ranges

Tags:

sql

mysql

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.

like image 278
HGF Avatar asked Jan 12 '23 05:01

HGF


2 Answers

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

like image 107
hjpotter92 Avatar answered Jan 13 '23 18:01

hjpotter92


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
like image 24
Arion Avatar answered Jan 13 '23 18:01

Arion