2012-01-30 39 views
2

我有一個數據庫,其中包含兩個我關心的日期。僅當前財年的動態SQL日期

起始日期+ 結束日期

這些日期都存儲在以下格式:

2008-06-23 00:00:00.000 

我需要添加一塊動態SQL只帶回落在當前財政年度日期。

因此例如01/04/2011 - 31/03/2012將是本財政年度。

Therfore衛生組織結束日期的任何記錄是這些日期內,或者是NULL被歸類爲「主動」

年部分將需要動態的,所以,一旦它擊中2012年4月1,我們搬進新財政年度,並將於2012年4月1日至2013年3月31日期間帶回數據,依此類推。

可以建議一些代碼或指出我忽略的任何規則嗎?

+1

難道不應該從01/04/2012 *回來 - 31/03/13 *? – RedFilter 2012-01-30 14:39:15

+0

是的,好喊 – JsonStatham 2012-01-30 14:40:30

+0

日期是真的以字符串的格式存儲,還是存儲在日期時間字段? – 2012-01-30 14:51:32

回答

3

嘗試:

... 
where StartDate >= 
    case 
     when month(getdate()) > 3 
      then convert(datetime, cast(year(getdate()) as varchar) + '-4-1') 
     else 
      convert(datetime, cast(year(getdate()) - 1 as varchar) + '-4-1') 
    end 
and (EndDate is null or EndDate < 
    case 
     when month(getdate()) > 3 
      then convert(datetime, cast(year(getdate()) + 1 as varchar) + '-4-1') 
     else 
      convert(datetime, cast(year(getdate()) as varchar) + '-4-1') 
    end) 
+0

更新where子句以處理NULL結束日期。 – RedFilter 2012-01-30 15:10:35

+0

沒有帶回任何東西時,有23條記錄這是elgible當前財政年度:enddates是: 01/06/2011 01/06/2011 01/06/2011 01/06/2011/06/2011 24/05/2011 05/10/2011 19/12/2011 24/11/2011 01/06/2011 14/10/2011 25/06/2011 04/04/2011 06/04/2011 07/04/2011 01/06/2011 02/06/2011 25/06/2011 24/11/2011 15/07/2011 01/04/2011 04/04/2011 23/11/2011 – JsonStatham 2012-01-30 15:13:28

+0

@G_Thang錯字,嘗試更新版本。 – RedFilter 2012-01-30 15:17:15

1

創建一個包含字段financial_year_startfinancial_year_end一個Finacial_Year查找表。

用接下來的50年數據填充它(使用電子表格來簡化日期)。

加入你的表使用enddate

SELECT ... 
FROM Your_Table LEFT JOIN Financial_Year 
ON Your_Table.enddate BETWEEN Financial_Year.financial_year_start 
    AND Financial_Year.financial_year_end 
WHERE Your_Table.enddate IS NULL -- Active 
    OR (getdate() BETWEEN Financial_Year.financial_year_start 
    AND Financial_Year.financial_year_end) 

在當前日期在接下來的兩個日期之間目前的金融會自動改變查找表。

順便說一句,英國的財政年度從06-04-YYYY延伸到05-04-YYYY,而不是從第1個到第31個。

2

在這裏,我們去:)

動態的解決方案,

DECLARE @MyDate DATETIME 
SET @MyDate = getDate() 

DECLARE @StartDate DATETIME 
DECLARE @EndDate DATETIME 

SET @StartDate = DATEADD(dd,0, DATEDIFF(dd,0, DATEADD(mm, -(((12 + DATEPART(m, @MyDate)) - 4)%12), @MyDate) - datePart(d,DATEADD(mm, -(((12 + DATEPART(m, @MyDate)) - 4)%12),@MyDate))+1)) 
SET @EndDate = DATEADD(ss,-1,DATEADD(mm,12,@StartDate)) 

SELECT @StartDate,@EndDate