SQL - Query para agrupar o número de itens (COUNT) em intervalos de valores (CASE WHEN)

15/12/2018

0

Olá pessoal, bom dia.
Sou novo aqui no fórum e também iniciante em SQL. Gostaria da ajuda de vocês para finalizar a query abaixo:

Preciso criar uma query que me dê a quantidade de pedidos por faixa de seus totais. O resultado final deve ficar assim:

k5 k10 k15 k20 acima20k TT
1030 84 10 4 8 1136

Para chegar nestes valores, tive que fazer 5 SELECTs e rodá-los separadamente:

select count (total) from pedidos where total <= 5000 and data between '2014-01-01' and '2014-12-31'
select count (total) from pedidos where total <= 10000 and total >5000 and data between '2014-01-01' and '2014-12-31'
select count (total) from pedidos where total <= 15000 and total >10000 and data between '2014-01-01' and '2014-12-31'
select count (total) from pedidos where total <= 20000 and total >15000 and data between '2014-01-01' and '2014-12-31'
select count (total) from pedidos where total >20000 and data between '2014-01-01' and '2014-12-31'

Daí tentei fazer tudo numa única query assim:

select
count (case when total <= 5000 then 1 else 0 end) as k5,
count (case when (total <= 10000 and total > 5000) then 1 else 0 end) as k10,
count (case when (total <= 15000 and total > 10000) then 1 else 0 end) as k15,
count (case when (total <= 20000 and total > 15000) then 1 else 0 end) as k20,
count (case when total > 20000 then 1 else 0 end) as acima20k,
count (total) as TT
from pedidos
where data between '2014-01-01' and '2014-12-31'

Mas o resultado que tive foi esse:

k5 k10 k15 k20 acima20k TT
1136 1136 1136 1136 1136 1136

Pelo que andei olhando na internet, um GROUP BY poderia me ajudar, mas não sei como fazê-lo.
Alguém consegue me dar uma luz nisso?
Hugo Campigotto

Hugo Campigotto

Responder

Post mais votado

15/12/2018

nesse caso, utilize sum() no lugar de count().
assim:
select
	sum(case when total <=  5000 then 1 else 0 end) as k5,
	sum(case when total  >  5000 and total <= 10000 then 1 else 0 end) as k10,
	sum(case when total  > 10000 and total <= 15000 then 1 else 0 end) as k15,
	sum(case when total  > 15000 and total <= 20000 then 1 else 0 end) as k20,
	sum(case when total  > 20000 then 1 else 0 end) as acima20k,
	count(total) as TT
from pedidos
	where data between '2014-01-01' and '2014-12-31'


Emerson Nascimento

Emerson Nascimento
Responder

Mais Posts

15/12/2018

Emerson Nascimento

Explicando a postagem:
count() - conta o número de registros com conteúdo. não faz diferença se é 0 ou 1, será um registro contado (só não conta se for null)
sum() - soma o conteúdo do campo.

Então, com a função count(), usa-se NULL para ignorar o registro:
select
	count(case when total <=  5000 then 1 else null end) as k5,
	count(case when total  >  5000 and total <= 10000 then 1 else null end) as k10,
	count(case when total  > 10000 and total <= 15000 then 1 else null end) as k15,
	count(case when total  > 15000 and total <= 20000 then 1 else null end) as k20,
	count(case when total  > 20000 then 1 else null end) as acima20k,
	count(total) as TT
from pedidos
	where data between '2014-01-01' and '2014-12-31'
com o uso da função count(), onde coloquei "then 1" poderia ser qualquer valor, por exemplo, "then 'A'", ou "then 350", ou "then getdate()" (qualquer conteúdo). Tente a instrução abaixo e você verá que também funcionará, porque basta que haja algum conteúdo no campo:
select
	count(case when total <=  5000 then 1 else null end) as k5,
	count(case when total  >  5000 and total <= 10000 then getdate() else null end) as k10,
	count(case when total  > 10000 and total <= 15000 then 'A' else null end) as k15,
	count(case when total  > 15000 and total <= 20000 then 350 else null end) as k20,
	count(case when total  > 20000 then 'TESTE' else null end) as acima20k,
	count(total) as TT
from pedidos
	where data between '2014-01-01' and '2014-12-31'

Com a função sum(), usa-se 0 para ignorar o registro:
select
	sum(case when total <=  5000 then 1 else 0 end) as k5,
	sum(case when total  >  5000 and total <= 10000 then 1 else 0 end) as k10,
	sum(case when total  > 10000 and total <= 15000 then 1 else 0 end) as k15,
	sum(case when total  > 15000 and total <= 20000 then 1 else 0 end) as k20,
	sum(case when total  > 20000 then 1 else 0 end) as acima20k,
	count(total) as TT
from pedidos
	where data between '2014-01-01' and '2014-12-31'

Responder

15/12/2018

Hugo Campigotto

nesse caso, utilize sum() no lugar de count().
assim:
select
	sum(case when total <=  5000 then 1 else 0 end) as k5,
	sum(case when total  >  5000 and total <= 10000 then 1 else 0 end) as k10,
	sum(case when total  > 10000 and total <= 15000 then 1 else 0 end) as k15,
	sum(case when total  > 15000 and total <= 20000 then 1 else 0 end) as k20,
	sum(case when total  > 20000 then 1 else 0 end) as acima20k,
	count(total) as TT
from pedidos
	where data between '2014-01-01' and '2014-12-31'





Ótimo, Emerson. Deu certinho. Muito obrigado.
Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar