Take Report with zero months

Asked

Viewed 102 times

2

I have a query in which I take monthly deposited values it takes everything it has in the base and shows the months that were entered in the base.

I would like to do different I would like to show also the months that had no deposit I would like to bring zeroed as the image below my bank is the Postgres.

How It Brings Today

inserir a descrição da imagem aqui

How Would You Like to Bring

inserir a descrição da imagem aqui

Query

SELECT to_char(fi.data,'yyyy/mm') as Mês, count(fi.*) as valor 
  FROM financeiro fi 
  WHERE fi.status = '1' 
  GROUP BY Mês 
  ORDER BY Mês;
  • A solution for Oracle, see help http://forum.imasters.com.br/topic/522521-forcar-select-trazer-linha-mesmo-que-sem-valor/

  • I tried to ride here but it didn’t work

  • will be by year, will have a filter?

  • http://forum.imasters.com.br/topic/278755-numero-da-linha-no-mysql-tipo-rownum-no-oracle/

  • For months @Virgilionovic

  • but for example you choose the year or this for you is helpless?

  • For now it’s indifferent

  • Is it Mysql or postgresql? Please specify, the solution may be different in each case.

  • I specified the Bank is Postgres

Show 4 more comments

3 answers

1

Make a outer join with generate_series:

select to_char(d.data,'yyyy/mm') as Mês, count(fi.*) as valor 
from
    financeiro fi
    right join
    generate_series(
        '2016-01-01'::date, '2016-12-01, '1 month'
    ) gs (d) on d = date_trunc('month', fi.data)
where fi.status = '1' 
group by mês 
order by mês;

0

You can also always use a CTE and a CASE (in postgres I always prefer to use CTE’s to improve reading and split kerys

WITH consulta AS (
SELECT to_char(fi.data,'yyyy/mm') as Mes, count(fi.*) as valor 
FROM financeiro fi 
WHERE fi.status = '1' 
GROUP BY Mês 
ORDER BY Mês;
)
SELECT mes, 
CASE WHEN valor IS NULL THEN '0'
ELSE valor
END
FROM consulta

0

To also display NULL values we need to use a function that replaces the null value with a desired value, in this case 0. Depending on the database you are using the syntax changes but in oracle is nvl([your field],0)

If your database is oracle try calling the value field like this:

nvl(fi.valor,0)
  • Thanks @Guilherme did not know this function I will try to use here and I’ll give you a feedback

Browser other questions tagged

You are not signed in. Login or sign up in order to post.