【问题标题】:Check how many DateTimes from a table fits between a range of DateTimes检查表中有多少 DateTimes 适合一系列 DateTimes
【发布时间】:2018-08-30 15:54:47
【问题描述】:
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' and dateto='2018-05-29'),结果应该是 1。

【问题讨论】:

  • 如果您指定 from=05-01 & to=08-15,结果会是 3 吗?

标签: sql tsql datetime


【解决方案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

【讨论】:

  • 尝试:设置@dateFrom = '2018-05-27',这种格式是全球性的,使用你的会根据服务器语言而改变
【解决方案2】:

我认为这是你想要的:

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

【讨论】:

    猜你喜欢
    • 2013-09-17
    • 1970-01-01
    • 2021-11-04
    • 2015-08-24
    • 2019-08-11
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多