我需要在sql server 2008中显示两个特定日期之间的所有日期吗? 该表包含日期,数量等字段,因此如果我给出日期= '01 / 06/2013'和todate = '05 / 06/2013',我需要显示这些日期之间的所有日期以及数量
输出如下:
Date(date datatype) Day Produced Qty
01-06-13 Saturday 400.00
02-06-13 Sunday 550.00
03-06-13 Monday 200.00
04-06-13 Tuesday 100.00
05-06-13 Wednsdy 250.00
Total 1500.00
请帮帮忙?
答案 0 :(得分:5)
尝试使用此...
Select date, day, produce_qty from Table
where date >= '03/06/2013' and date < '05/06/2013'
或者
Select date, day, produce_qty from Table
where date BETWEEN '03/06/2013' and '05/06/2013'
答案 1 :(得分:1)
这将为您提供一个日期表,您可以OUTER JOIN
使用您的数据:
declare @Start as Date = '20130501';
declare @End as Date = '20130515';
with Dates as (
select @Start as [ReportDate]
union all
select DateAdd( day, 1, ReportDate )
from Dates
where ReportDate < @End )
select ReportDate
from Dates option ( MaxRecursion 0 );
编辑:或者,使用示例数据:
declare @Production as Table ( ActivityDate Date, ProductionQuantity Int );
insert into @Production ( ActivityDate, ProductionQuantity ) values
( '20130106', 400 ),
( '20130112', 550 ),
( '20130112', 50 );
declare @Start as Date = '20130101';
declare @End as Date = '20130115';
with Dates as (
select @Start as [ReportDate]
union all
select DateAdd( day, 1, ReportDate )
from Dates
where ReportDate < @End )
select ReportDate, Coalesce( Sum( P.ProductionQuantity ), 0 ) as Qty
from Dates as D left outer join
@Production as P on P.ActivityDate = D.ReportDate
group by D.ReportDate
option ( MaxRecursion 0 );