检查一个表中有多少个DateTime可以容纳一系列的DateTimes

时间:2018-08-30 15:54:47

标签: sql tsql datetime

DECLARE @dateFrom   DATETIME;
DECLARE @dateTo     DATETIME;

declare @tempholidays table (holidays datetime);

insert into @tempholidays values(CONVERT(datetime, '2018-01-01'));
insert into @tempholidays values(CONVERT(datetime, '2018-02-19'));
insert into @tempholidays values(CONVERT(datetime, '2018-04-06'));
insert into @tempholidays values(CONVERT(datetime, '2018-04-09'));
insert into @tempholidays values(CONVERT(datetime, '2018-05-01'));
insert into @tempholidays values(CONVERT(datetime, '2018-05-28'));
insert into @tempholidays values(CONVERT(datetime, '2018-08-15'));
insert into @tempholidays values(CONVERT(datetime, '2018-12-25'));
insert into @tempholidays values(CONVERT(datetime, '2018-12-26'));

我有一个带有一些日期时间的临时表。 我想知道在特定的日期时间范围(dateFrom,dateTo)中存在多少这些条目。例如,如果我给出范围(datefrom ='2018-05-27'和dateto ='2018-05-29'),结果应为1。

2 个答案:

答案 0 :(得分:1)

DECLARE @dateFrom   DATETIME;
DECLARE @dateTo     DATETIME;

declare @tempholidays table (holidays datetime);

insert into @tempholidays values(CONVERT(datetime, '2018-01-01'));
insert into @tempholidays values(CONVERT(datetime, '2018-02-19'));
insert into @tempholidays values(CONVERT(datetime, '2018-04-06'));
insert into @tempholidays values(CONVERT(datetime, '2018-04-09'));
insert into @tempholidays values(CONVERT(datetime, '2018-05-01'));
insert into @tempholidays values(CONVERT(datetime, '2018-05-28'));
insert into @tempholidays values(CONVERT(datetime, '2018-08-15'));
insert into @tempholidays values(CONVERT(datetime, '2018-12-25'));
insert into @tempholidays values(CONVERT(datetime, '2018-12-26'));

set @dateFrom = 'May 27, 2018'
set @dateTo = 'May 29, 2018'

select
    count(*) countx
from
    @tempholidays h
where
    h.holidays between @dateFrom and @dateTo

答案 1 :(得分:0)

我认为这可以满足您的要求

select count(*)
from @tempholidays th
where th.date >= @datefrom and th.date <= @dateto;