簡體   English   中英

比較SQL Server數據庫中的DateTime列

[英]Compare DateTime column in SQL Server database

我在SQL Server 2008表中有一列DateTime類型(稱為“ FinalizedDate”)。 該列包含可以追溯到幾年前的記錄。

我需要獲取屬於“當前操作數據”中的那些行。 它定義為:

如果當前日期在5月1日之前,則從前一年的10月1日到5月1日;如果當前日期在10月1日之后,則從本年的10月1日到次年的5月1日。

例如,

FinalisedDate

2013-04-15 00:00:00.000
2013-07-01 00:00:00.000
2013-10-01 00:00:00.000    //the current operational data
2013-11-15 00:00:00.000    //the current operational data
2013-12-30 00:00:00.000    //the current operational data
2014-01-15 00:00:00.000    //the current operational data
2014-03-01 00:00:00.000    //the current operational data
2014-04-15 00:00:00.000    //the current operational data
2014-05-30 00:00:00.000
2014-09-01 00:00:00.000

任何人都可以提供解決方案以獲取當前運營年度的所有行嗎? 提前致謝。

干杯,亞歷克斯

我的建議是采用這種方法。 從兩個DateTime變量開始:

declare @StartDate as datetime, @EndDate as datetime

然后查看當前日期,並使用條件邏輯為這些變量分配值。 然后執行以下操作:

where FinalizedDate >= @StartDate
and FinalizedDate < Dateadd(day, 1, @EndDate)

您會自己解決邏輯部分而感到困惑。

編輯從這里開始

但是,這是一個創可貼的解決方案。 您將受益於日歷表,即以日期為主鍵和其他必填字段的表。 這些字段之一將是OperationalYear,其值將為'2013/14','2014/15'等。

然后,您可能會這樣:

from thistable join CalendarTable on FinalizedDate = TheDate 
where OperationalYear = (subquery that gets OperationalYear from GetDate())

我會定期在另一個函數中計算日期范圍,然后簡單地執行一次之間查詢,但類似

Declare @startDate DateTime
Declare @endDate DateTime
Declare @offset int
set @Offset = 0
if Month(GetDate()) < 5
begin
  set @offset = -1
end

set @startDate = Convert(DateTime,Convert(VarChar(4),Year(GetDate())  - offset) + '1001',112)
set @endDate = DateSubtract(day,1,DateAdd(year,1,@startDate))
select * from MyTable Where FinalizedDate Between @startDate and @endDate

應該做的工作

SELECT *
FROM MyTable
CROSS APPLY (
  SELECT CASE
    WHEN MONTH(currentdate) <   5 THEN YEAR(currentdate)-1
    WHEN MONTH(currentdate) >= 10 THEN YEAR(currentdate)
    END
  FROM (SELECT GETDATE()) t1(currentdate)
  ) t2(opyear)
WHERE FinalisedDate >= DATEFROMPARTS(opyear  ,10,1)
  AND FinalisedDate <  DATEFROMPARTS(opyear+1, 5,1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM