I
I
Ilya2019-09-20 11:53:36
SQL
Ilya, 2019-09-20 11:53:36

How to optimize multiple count(case ...)?

I have a query like:

select 
count (case when sum >= 0 and sum <= 100 then id end) as '0-100',
count (case when sum >= 101 and sum <= 200 then id end) as '101-200',
count (case when sum >= 201 and sum <= 300 then id end) as '201-300',
count (case when sum >= 301 and sum <= 400 then id end) as '301-400',
count (case when sum >= 401 and sum <= 500 then id end) as '401-500'
from ...

Those. I just count the number of id, the values ​​of the sum field for which are included in the specified range, it turns out quite cumbersome (I have more of these counts than in the example). But I can’t think of how it can be reduced / optimized, I have little experience.
Tell me, is it possible and how? :)
ps between instead of >= <= do not offer, it's more convenient for me)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Adamos, 2019-09-20
@Cor4win

SELECT COUNT(1), 100 * FLOOR(sum / 100) FROM ... GROUP BY FLOOR(sum / 100)

L
Lazy @BojackHorseman, 2019-09-20
SQL

by what criterion to optimize?) from the point of view of the execution plan, there is nowhere to optimize further)
can be written a little shorter =))

SELECT
SUM(sum BETWEEN 0 AND 100) AS '0-100',
SUM(sum BETWEEN 101 AND 200) AS '101-200'
/* ... */
FROM ...

but it doesn't change the point.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question