我目前有一张包含创建日期和到期日期的表格。我目前有一个sql命令来获取给定日期的有效项目数。
select
count(id) ,CONVERT(date, getdate())
from
table
where
createDate < getdate() and expDate > getdate()
这将返回计数和当前日期。
是否可以编写一个sql查询来返回一系列日期的结果,比方说我想在15天的范围内绘制有效项目的数量?
谢谢!
答案 0 :(得分:2)
检查一下,
DECLARE @StartDate DATETIME,
@EndDate DATETIME;
SELECT @StartDate = '20110501'
,@EndDate = '20110801';
SELECT
DATEADD(d, x.number, @StartDate) AS MonthName1
,
x.number
FROM master.dbo.spt_values x
WHERE x.type = 'P'
AND x.number <= DATEDIFF(MONTH, @StartDate, @EndDate);
上述查询提供了2个日期之间的日期列表。
根据您的表格和问题,请同时查看。
declare @table table(id int,frdt datetime, todt datetime)
insert into @table values (1,GETDATE()-20, GETDATE()-19)
,(2,GETDATE()-9, GETDATE()-8)
,(3,GETDATE()+20, GETDATE()+18)
,(4,GETDATE(), GETDATE()-1)
,(5,GETDATE()-20, GETDATE())
,(6,GETDATE()-10, GETDATE()+10 )
select * from @table
declare @frdt datetime = null , @todt datetime = getdate()-10
select @frdt, @todt,* from @table
where
(@frdt is null or @frdt between frdt and todt)
and
(@todt is null or @todt between frdt and todt)
select @frdt = GETDATE()-15 , @todt = GETDATE()
select @frdt, @todt,* from @table
where
(@frdt is null or @frdt between frdt and todt)
and
(@todt is null or @todt between frdt and todt)
答案 1 :(得分:2)
试试这个:
create table #datelist (ValidDateCheck date, ValidResults int)
declare @startdate date = '1/1/2015'
declare @enddate date = '2/1/2015'
declare @interval int = 1 --Use 1 if you want every day between your dates, use 2 if you want every other day, etc.
declare @datecounter date = @startdate
declare @count int
while @datecounter <= @enddate
begin
set @count =
(select count(*)
from Table
where CrtDt <= @datecounter and ExpDt > @datecounter)
insert into #datelist values (@datecounter, @count)
set @datecounter = dateadd(dd, @interval, @datecounter)
end
select * from #datelist order by 1
它遍历您范围内的所有日期,计算每个日期的有效结果。