码迷,mamicode.com
首页 > 数据库 > 详细

sql 时间段内没有的数据等于0

时间:2016-09-27 23:16:19      阅读:324      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

如何实现没有的时间段中使用0来填充??

if object_id([A]) is not null drop table [A]
go 
create table [A]([日期] datetime,[金额] int)
insert [A]
select * from [A]
select 2014-05-01,100 union all
select 2014-05-02,200 union all
select 2014-05-05,300 union all
select 2014-05-06,200

declare @stdate smalldatetime,
        @eddate smalldatetime
select  @stdate=min([日期]),
        @eddate=max([日期]) from [A]
;
with sel as
(
 select @stdate as [date],1 as val
 union all
 select  dateadd(day,val,@stdate),val+1 as val from sel where val<=datediff(day,@stdate,@eddate)
)
select sel.[date] as [日期],sum(isnull(A.[金额],0)) as [金额] from sel
left join [A] on sel.[date]=[A].[日期] group by sel.[date]

解释一下:with这一步是关键,通过它使得“select dateadd(day,val,@stdate),val+1 as val from sel where val<=datediff(day,@stdate,@eddate)”一直在查询时间差

然后通过外链接关联

 

sql 时间段内没有的数据等于0

标签:

原文地址:http://www.cnblogs.com/panmy/p/5914521.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!