释
有2个工作班次,白班=从07:00:00
到19:00:00
,夜班=从19:00:00
到07:00:00
示例数据
Name Date Time WorkShift
John 2015-09-14 19:14:24 N
John 2015-09-14 23:43:27 N
John 2015-09-15 03:21:36 N
John 2015-09-15 11:29:48 D
期望的结果
例如,我有@dateStart = 2015-09-14
和@dateEnd = 2015-09-14
个变量。我需要在以下内容中选择2015-09-14 19:00:00
到2015-09-15 07:00:00
的记录:
John 2015-09-14 19:14:24 N
John 2015-09-14 23:43:27 N
John 2015-09-15 03:21:36 N
如上所示,此处为日期2015-09-15
,但Time
为03:21:36
,因此应选择它(因为时间低于07:00:00
,{{1} } workshift)。
问题
我的查询按预期选择,但有2个问题。
如果我通过N
和@dateStart = 2015-09-15
选择:
@dateEnd = 2015-09-15
另一个问题是如果我有这样的记录
John 2015-09-15 03:21:36 N -- this shouldn't be selected again, this should go as 2015-09-14
John 2015-09-15 11:29:48 D
如您所见John 2015-09-15 03:21:36 N
中John
没有任何记录所以当我在以下内容中传递变量时应该选择它:2015-09-14
和@dateStart = 2015-09-15
QUERY
@dateEnd = 2015-09-15
如果事情不清楚 - 问我,我会尝试解释。
答案 0 :(得分:2)
如何在开始和结束时间添加小时数?
where datetime >= dateadd(hour, 19, @datestart) and
datetime < dateadd(hour, 7, @dateend)
如果您将“日期”和“时间”存储在不同的列中(通常不推荐),您可以在转换为datetime
后添加它们:
where cast(date as datetime) + cast(time as datetime) >= dateadd(hour, 19, @datestart) and
cast(date as datetime) + cast(time as datetime) < dateadd(hour, 7, @dateend)
答案 1 :(得分:1)
尝试这个
select *
from SampleTable
where convert(dateTime,DateCreated) + convert(dateTime,StartTime)
between DATEADD(HH,7, @dateStart) and DATEADD(HH,24+7, @dateEnd)
or
(
convert(dateTime,DateCreated) + convert(dateTime,StartTime)
between DATEADD(HH,00, @dateStart) and DATEADD(HH,7, @dateStart) -- Morning records
and not exists
(
select 1 from SampleTable where
convert(dateTime,DateCreated) + convert(dateTime,StartTime)
between DATEADD(HH,7-24, @dateStart) and DATEADD(HH,0, @dateStart)
) -- Data from previous day
)