I'm trying to put together a query that answers the following question:
Number of customers (registration in the case) that has a 26-day reading date, number of clients that have 27-day reading, and so on up to 31 days, I will show an image exactly what I want:
My query is not returning what I want, it is returning zero in every QTD_DIAS column, the query is conforming to the image (I put it after the order by the dat_read, ta)
So, I believe I need to do some kind of subquery, but I do not know where to start, could anyone help me? Thank you so much!
select distinct top 10 sigla_unidade AS UNIDADE
, dsc_localidade as LOCALIDADE
, o.competencia AS COMPETENCIA
--, DAT_LEITURA AS QTD_DIAS
, lead(dat_leitura, 1) over (PARTITION by dat_leitura order by) prox_leitura
, datediff(day, dat_leitura, lead(dat_leitura, 1) over(PARTITION by dat_leitura)) QTD_DIAS
, o.inscricao as QTD_INSCRICOES
from BASE o
join USUARIOS u
on o.inscricao = u.inscricao
join UNIDADES n
on u.cod_und_negocio = n.cod_unid_negocio
join LOCALIDADES 1
on u.localidade = 1.cod_localidade
--group by sigla_unidade, desc_localidade, o.competencia, dat_leitura, a.inscricao