显示两个日期之间的所有日期数据;如果特定日期不存在行,则所有列中显示零
我想显示两个日期之间的所有日期,当缺少任何日期数据时,它应该在 val 列中显示零。
declare @temp table (
id int identity(1,1) not null,
CDate smalldatetime ,
val int
)
插入要检查的数据语句
insert into @temp select '10/2/2012',1
insert into @temp select '10/3/2012',1
insert into @temp select '10/5/2012',1
insert into @temp select '10/7/2012',2
insert into @temp select '10/9/2012',2
insert into @temp select '10/10/2012',2
insert into @temp select '10/13/2012',2
insert into @temp select '10/15/2012',2
检索当月第一天和今天之间的记录
select * from @temp where CDate between '10/01/2012' AND '10/15/2012'
当我运行此查询时,它会显示这两个日期之间的所有数据,但我还想使用 val=0
I want to show all dates between two dates when there is any date data missing then its should show zero in val column .
declare @temp table (
id int identity(1,1) not null,
CDate smalldatetime ,
val int
)
INSERT STATEMENT FOR DATA TO CHECK
insert into @temp select '10/2/2012',1
insert into @temp select '10/3/2012',1
insert into @temp select '10/5/2012',1
insert into @temp select '10/7/2012',2
insert into @temp select '10/9/2012',2
insert into @temp select '10/10/2012',2
insert into @temp select '10/13/2012',2
insert into @temp select '10/15/2012',2
Retrieve records between first day of month and today
select * from @temp where CDate between '10/01/2012' AND '10/15/2012'
As i run this query its show me all data between these two dates but i want to also include missing dates with val=0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要弥补日期,因此我在这里使用了递归公用表表达式。
SQL Fiddle
You need to make up the dates, so I've use a recursive common table expression here.
SQL Fiddle
只要从日期到结束日期之间的天数少于 2047 天,此操作就有效
This will work as long as there are less than 2047 days between from and to dates
我认为最好的方法是使用日期创建自己的表(您也可以使用 master.dbo.spt_values,但我个人不喜欢该解决方案)
您也可以使用 CTE 的递归解决方案
I think the best way to do this is to create your own table with dates (you can also use master.dbo.spt_values, but I personally don't like that solution)
you can also use recursive solution with CTE
使用具有最小值和最大值的递归 cte
using a recursive cte with min and max