2013-08-29 32 views
-1

我有兩個日期,從日期到日期如何選擇使用where子句?

另外我有兩個時間字段,從時間到時間

數據庫中的日期字段是Datetime。我需要根據日期和時間選擇數據。

這是我選擇的數據13:00 至15:00查詢,但它不適合20:00至08:00

where Date>= '2/01/2012' AND Date<'2/28/2013' 
    AND CAST(Date AS TIME) BETWEEN '20:00' AND '08:00' 
+1

你必須拿出兩個日期時間值做得到正確的邏輯。爲此,您可能必須先將日期和時間值轉換爲字符串,然後將字符串轉換爲日期時間。比我聰明的人可能會知道如何直接做到這一點。 –

+0

您是否只想返回輸入間隔完全在行間隔中的行?或者也部分 – Hazaart

+0

請檢查我的更新回答 – htxryan

回答

2

沒有看到您的特定錯誤/意想不到的結果,我認爲這個問題是20比8更大。

你將不得不使用兩個條件:

where Date>= '2/01/2012' AND Date<'2/28/2013' AND (CAST(Date AS TIME) > '20:00' OR CAST(Date AS TIME) < '08:00') 

編輯:固定狀態

+2

'CAST(日期AS TIME)> '20:00'和CAST(日期AS TIME)<'08:00''將始終爲假。 – TToni

+0

@Toni正確的你!更新了答案。 – htxryan

2

這是你所追求的?

WHERE Date BETWEEN '2012-01-01 20:00:00.000' AND '2012-12-01 08:00:00.000' 

有點不清楚你是否試圖動態地生成WHERE子句變量?

+0

這應該是一個原始問題花花公子的評論:) – gvee

+0

是的,我需要這種類型的過濾 –

+0

在這種情況下,這是解決還是你需要更多的信息? – Yonabart

0

您需要將「日期」和「時間」部分組合在一起。

此代碼將說明如何做到這一點:

SELECT the_date 
    , the_time 
    , DateAdd(hh, DatePart(hh, the_time), the_date) As hour_added 
    , DateAdd(mi, DatePart(mi, the_time), the_date) As minute_added 
    , DateAdd(mi, DatePart(mi, the_time), DateAdd(hh, DatePart(hh, the_time), the_date)) As both_added 
FROM (
     SELECT Cast('2013-02-28' As datetime) As the_date 
      , Cast('08:30' As datetime) As the_time 
     ) As example 

然後可以使用所得到的值在比較