while循环中的日期列表

时间:2017-05-01 14:41:03

标签: sql datetime while-loop ssms sql-server-2014

我有以下while循环:

DECLARE @Date Date

DECLARE @Trucks INT

DECLARE @MaxTrucks INT

SET @Date = DATEADD(mm, -1,DATEADD(mm, DATEDIFF(mm,0,GETDATE()),0)) 

SET @Trucks = 0

SET @MaxTrucks = 0

WHILE @Date < DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0) 

BEGIN
SET @Trucks = (

SELECT COUNT(DISTINCT([TruckID]))

FROM TruckAvailability

WHERE CONVERT(Date,PlannedStartDT) <= @Date and CONVERT(Date,PlannedEndDT) >=

 @Date and TotalTicks > 0)

IF @Trucks > @MaxTrucks BEGIN SET @MaxTrucks = @Trucks END

SET @Date = DATEADD(day,1,@Date)

END

我现在需要的是MaxTrucks每个日期。这是一个包含日期的列和一个具有相应MaxTrucks的列。

亲切的问候

1 个答案:

答案 0 :(得分:1)

您可以使用日历或日期表进行此类操作。

对于内存中只有152kb,您可以在表格中拥有30年的日期:

/* dates table */
declare @fromdate date = '20000101';
declare @years    int  = 30;
/* 30 years, 19 used data pages ~152kb in memory, ~264kb on disk */
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
select top (datediff(day, @fromdate,dateadd(year,@years,@fromdate)))
    [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
into dbo.Dates
from n as deka cross join n as hecto cross join n as kilo
               cross join n as tenK  cross join n as hundredK
order by [Date];
create unique clustered index ix_dbo_Dates_date on dbo.Dates([Date]);

如果不采取创建表格的实际步骤,您可以使用common table expression生成一个日期临时表,只需:{/ p>

declare @fromdate date = dateadd(month, datediff(month, 0, getdate() )-1, 0);
declare @thrudate date = dateadd(day,-1,dateadd(month, datediff(month, 0, getdate() ), 0));
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, @thrudate)+1) 
      [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
  from n as deka cross join n as hecto cross join n as kilo
                cross join n as tenK cross join n as hundredK
   order by [Date]
)
select [Date]
from dates;

使用如下:

select top 1
    d.Date
  , MaxTrucks = count(distinct(ta.TruckId)) desc
from TruckAvailability ta
  inner join dates d
    on d.Date >= convert(date,ta.PlannedStartDT) 
   and d.Date <= convert(date,ta.PlannedEndDT)
where ta.TotalTicks > 0
group by d.Date
order by count(distinct(ta.TruckId)) desc

数字和日历表参考: