0

我需要在 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 

请帮忙?

4

2 回答 2

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'
于 2013-06-01T13:00:30.607 回答
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 );
于 2013-06-01T15:07:05.297 回答