Delete Report with months reset

1

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

I would like to do different would like it to also show the months that did not have deposit I would like to bring zeroed according to the image below my bank is Postgres.

How to Bring Today

HowIWouldLiketoBring

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;
    
asked by anonymous 08.11.2016 / 16:19

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;
    
11.11.2016 / 20:19
0

In order to display the 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 it is nvl ([your field] , 0)

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

nvl(fi.valor,0)
    
10.11.2016 / 19:22
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 the querys

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
    
25.05.2018 / 20:07