2015-09-15 180 views
1

闡釋自定義時間範圍

有2個工作班次,白班=從07:00:0019:00:00和夜班=從19:00:0007: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,但Time03:21:36所以應該選擇(因爲時間低於07:00:00N輪班)。


問題

我的查詢選擇符合市場預期,但也有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-14John記錄,以便當我通過以下變量時應該選擇它:@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) 

如果有什麼不清楚 - 問我,我會盡量解釋。

+0

有一次,當我在考勤註冊程序中遇到類似問題時,我不得不使用AM/PM的時間戳,並檢查相同的問題以解決問題。我認爲它可以幫助你。爲什麼不檢查那種方式? –

+0

在DATE數據類型中不採用datetime值並將其存儲爲varchar的具體原因是什麼? –

+0

@RahulTripathi不,沒有任何具體的原因,只是沒有想法如何以其他方式使它。 –

回答

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 
) 
+0

感謝您的回答,但似乎是錯誤的。它返回相同的結果爲14天,相同的結果爲15天(如示例) –

+0

明白了。對於每一天,你只需要白天和晚上......如果沒有前一天的數據,你需要選擇早晨記錄的行。更新的解決方案 –

+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)