闡釋自定義時間範圍
有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
,N
輪班)。
問題
我的查詢選擇符合市場預期,但也有2個問題。
如果我通過@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
紀錄正如你看到的,沒有任何2015-09-14
爲John
記錄,以便當我通過以下變量時應該選擇它:@dateStart = 2015-09-15
和@dateEnd = 2015-09-15
QUERY
select *
from SampleTable
where /* Some conditions.... and*/
(convert(date, StartTime) >= @dateStart) and
(case when (DateCreated between cast(cast(cast(DateCreated as date) as varchar(40)) + ' 19:00:00' as datetime)
and cast(cast(cast(DateCreated as date) as varchar(40)) + ' 23:59:59' as datetime)
or
DateCreated between cast(cast(cast(DateCreated as date) as varchar(40)) + ' 00:00:00' as datetime)
and cast(cast(cast(DateCreated as date) as varchar(40)) + ' 07:00:00' as datetime)
)
and Workshift like '%N'
then dateadd(day,-1,cast(cast(DateCreated as date) as varchar(40)))
else DateCreated
end <= @dateEnd)
如果有什麼不清楚 - 問我,我會盡量解釋。
有一次,當我在考勤註冊程序中遇到類似問題時,我不得不使用AM/PM的時間戳,並檢查相同的問題以解決問題。我認爲它可以幫助你。爲什麼不檢查那種方式? –
在DATE數據類型中不採用datetime值並將其存儲爲varchar的具體原因是什麼? –
@RahulTripathi不,沒有任何具體的原因,只是沒有想法如何以其他方式使它。 –