例如:当前为第10周,查询第7,8,9三周的数据。如果第8周没有数据,显示则为如下:
注 :数据库没有第八周的数据。(包括时间)
周数 列1
9 2
8 0
7 3
这个问题分两种情况;
第一种是你的周日期数据会自动显示的,举个例子,即使第八周没有数据,也会显示出周的日期,如下表(表名:tablea,null表示数据为空)
周日期 数据
2018-03-12 xksd
2018-03-05 wqsa
2018-03-04 null
2018-03-11 null
2018-02-28 ghr
2018-03-09 wqr
2018-02-27 qweojnnd
这种情况下只需要:
select 周日期,count(1) as ‘数量’ from tablea where 周日期 between dateadd(ww,-3,convert(varchar(10),getdate(),120)) and convert(varchar(10),getdate(),120) group by 周日期 ;
第二种情况:就是如果前一周的数据没有,就不会显示的话如图tableB:
周日期 数据
2018-03-12 xksd
2018-03-05 wqsa
2018-02-28 ghr
2018-03-09 wqr
2018-02-27 qweojnnd
这种时候你还要你想要的显示结果的话,你要先生成时间维度表,具体生成方法可参考:https://www.cnblogs.com/wxjnew/p/5057713.html
这样就能得到一个时间维度表dimdate;语句改为:
select
D.日期
,count(1) as ‘数量’
from dimdate D
left join tableb B
on D.日期=B.日期
where D.日期 between dateadd(ww,-3,convert(varchar(10),getdate(),120)) and convert(varchar(10),getdate(),120)
group by D.日期 ;
希望能解决你的问题!
select * from tablea where datecol between dateadd(ww,-3,convert(varchar(10),getdate(),120)) and convert(varchar(10),getdate(),120);
select * from tablea where datecol between dateadd(ww,-3,convert(varchar(10),getdate(),120)) and convert(varchar(10),getdate(),120);;;
select * from tablea where datecol in dateadd(ww,-3,convert(varchar(10),getdate(),120)) and convert(varchar(10),getdate(),120);