A solution is to create an auxiliary structure with the date range for which you want to generate the results.
If you want to use this solution, you have several alternatives (the list is not exhaustive):
- Create a physical table in the database that contains, for example,
all dates since the year 2000;
- Create a temporary table with a
date range;
- Use a CTE;
I’ll leave a solution here using a CTE.
create table tabela1
(
conta nvarchar(05),
[data] datetime,
valor float
);
insert into tabela1(conta, [data], valor)values
('12345', '2016-05-25', 1),
('12345', '2016-05-26', 3),
('12345', '2016-05-26', 1),
('12345', '2016-05-28', 2),
('12345', '2016-05-28', 3);
with Datas as (
select cast('2016-05-25' as date) [data]
union all
select dateadd(dd, 1, t.[data])
from Datas t
where dateadd(dd, 1, t.[data]) <= '2016-05-31'
) -- gera uma view descartável com o intervalo de datas entre 25 a 31 de Maio
select d.[data],
isnull(sum(valor), 0) sum_valor
from Datas d
left join tabela1 t
on t.[data] = d.[data]
and t.conta = '12345'
group by d.[data]
order by d.[data]
The previous statement will generate the following output:
data sum_valor
2016-05-25 1
2016-05-26 4
2016-05-27 0
2016-05-28 5
2016-05-29 0
2016-05-30 0
2016-05-31 0
Stay here the Sqlfiddle
So Diego, I would like to demonstrate along with the result presented the dates that had no record, in my sentence only brings the dates that had registered in the bank
– Rafael
I edited the answer, test now.
– Diego
The one that passed me also brings back only the days that had the records
– Rafael
Try to change the COALESCE to IFNULL then.
– Diego
hasn’t worked yet, I tried something like, only CT brings the dates, when I relate only the dates with values
– Rafael
with dateRange as
(
 select dt = startDate
 where startDate < endDate
 union all
 select dateadd(dd, 1, dt)
 from dateRange
 where dateadd(dd, 1, dt) <= @endDate
)
/ select Convert(varchar(MAX),dt,103) from dateRange/ select Convert(varchar(MAX),d.dt,103), COALESCE(SUM(VALLAN),NULL) from dateRange as d LEFT Join ARQ032 as t.DATLAN = d.dt WHERE t.NUMCON = '176087' GROUP BY d.dt
– Rafael
I tested the question select here and brings 0 where it has no value. Test in SQL only it to see.
– Diego
I tested it, it only brings the dates that have value SELECT DATLAN, COALESCE(SUM(VALLAN),0) FROM ARQ032 WHERE NUMCON = '176087' AND DATLAN >= '2016-01-01' AND DATLAN <= '2016-01-31' GROUP BY DATLAN ORDER BY DATLAN
– Rafael
The value field is null or has zero saved?
– Diego
Let’s go continue this discussion in chat.
– Diego
He has no movement, no record. in the example I sent I’m adding the amounts that have dates, the other dates of the month have no record in the bank
– Rafael