计算过去10天的数据,包括没有任何条目的天数

时间:2017-01-31 17:19:59

标签: sql sql-server database

我想计算过去10天中每个列具有特定值的所有数据。我设法做到了:

declare @start datetime = CAST(getdate() as date)
declare @end  datetime = dateadd(day, -10, @start)

;with amonth(day) as
(
     select @end as day
        union all
     select day + 1
        from amonth where day < CAST(@start as date)
)

select CAST(amonth.day as date) as dat, count(vrijeme) as c
from amonth 
left join Dnevnik on CAST(vrijeme as date) = CAST(amonth.day as date)
group by CAST(amonth.day as date) order by dat 

它给我一个这样的结果:

dat         c

2017-01-21  0     <--- day without any record
2017-01-22  1
2017-01-23  1
2017-01-24  1
2017-01-25  1
2017-01-26  0     <--- day without any record
2017-01-27  27
2017-01-28  125
2017-01-29  190
2017-01-30  127
2017-01-31  319

但我不想计算每一天的所有数据,我想计算一列具有特定值的数据。所以我认为它可能是这样的(我添加了where子句):

declare @start datetime = CAST(getdate() as date)
declare @end  datetime = dateadd(day, -10, @start)

;with amonth(day) as
(
   select @end as day
       union all
   select day + 1
       from amonth
       where day < CAST(@start as date)
)
select CAST(amonth.day as date) as dat, count(vrijeme) as c 
from amonth 
left join Dnevnik on CAST(vrijeme as date) = CAST(amonth.day as date) 
where tipZapisa = 6
group by CAST(amonth.day as date) order by dat 

但是这段代码给出的结果是没有空的日子(其中count为0)

dat          c

2017-01-22  1
2017-01-27  9
2017-01-28  67
2017-01-29  33
2017-01-30  46
2017-01-31  37

在上一个结果中,我只想包括没有任何记录的日子。

提前致谢

2 个答案:

答案 0 :(得分:2)

保持连接LEFT,停止在NULL中使用LEFT列 - 禁止WHERE中的谓词。将其包含在ON

with amonth(day) as
(
   select @end as day
       union all
   select day + 1
       from amonth
       where day < CAST(@start as date)
)
select CAST(amonth.day as date) as dat, count(vrijeme) as c 
from amonth 
left join Dnevnik on CAST(vrijeme as date) = CAST(amonth.day as date) 
                     and tipZapisa = 6
group by CAST(amonth.day as date) order by dat 

答案 1 :(得分:0)

预先填充@START以及第10个匹配记录的日期,然后将其提供给您的第二个查询

SELECT @START = MIN(DQ.dat) FROM (select DISTINCT TOP 10 CAST(amonth.day as date) as dat
from  Dnevnik WHERE tipZapisa = 6 ORDER BY amonth.day as date DESC) DQ

然后你应该能够返回具有匹配条件的实际10天