2013-06-01 57 views
0

我需要顯示SQL Server 2008中兩個特定日期之間的所有日期? 該表格包含日期,數量等字段,所以如果我給出從'date/'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

什麼數據類型是'日期'列? –

+1

另外,作爲一個數據庫正常化的事情,你不應該存儲星期幾。 –

+0

您是否問如何在範圍內爲_every_日期生成輸出,即使該表不包含某些日期的數據? – HABO

回答

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

這會給你日期的表格,你可以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); 
相關問題