2017-08-09 23 views
2

我試圖獲取發票日期和財政期間和年份。將month()函數與Case一起使用可以獲得期間。因爲第一階段是在11月份,所以我需要在這一年做+1 1如果/然後/否則格式化日期

使用IF函數和日期函數一起工作對我來說很有用。

我的查詢是

Select a.OrderAccount 
,a.InvoiceAccount 
,a.InvoiceDate 
,year(a.InvoiceDate) as Year 
,month(a.InvoiceDate) as Month, 
Case month(a.InvoiceDate) 
WHEN '11' THEN '1' -- increase year by +1 
WHEN '12' THEN '2'-- increase year by +1 
WHEN '1' THEN '3' 
WHEN '2' THEN '4' 
WHEN '3' THEN '5' 

任何意見,將不勝感激。由於

+2

製作一個包含會計期間的表格。加入並比較日期。然後,您可以在查詢中隨時使用財務週期表。 –

+0

Aside:好奇的是,你的'case'表達式除了'month(a.InvoiceDate)'以外的所有內容都使用字符串值。根據[數據類型優先順序](https://docs.microsoft.com/en-us/sql/t-sql/data-types/data-type-precedence-transact-sql),每個'when'值將被轉換比較之前爲整數。 'then'值將保持字符串。提示:使用合適的軟件(MySQL,Oracle,DB2,...)和版本(例如, '的SQL服務器2014'。請注意,'tsql'縮小了選擇範圍,但不指定數據庫。 – HABO

回答

6

使用DATEADD只加2個月來的原始日期:

MONTH(DATEADD(month,2,a.InvoiceDate)) as FiscalMonth, 
YEAR(DATEADD(month,2,a.InvoiceDate)) AS FiscalYear, 
0

如果你想堅持的算術:會計月份是(Month(a.InvoiceDate) + 1) % 12 + 1和值添加到日曆年度獲得財政一年是Month(a.InvoiceDate)/11

下面的代碼演示12個月:

with Months as (
    select 1 as M 
    union all 
    select M + 1 
    from Months 
    where M < 12) 
    select M, (M + 1) % 12 + 1 as FM, M/11 as FYOffset 
    from Months; 

d士丹利的答案讓你的意圖更加清晰,總是可維護性考慮。

1

創建並填充Calendar Table(它使日期工作更容易)。

create table Calendar 
(
    id int primary key identity, 
    [date] datetime, 
    [day] as datepart(day, [date]) persisted, 
    [month] as datepart(month, [date]) persisted, 
    [year] as datepart(year, [date]) persisted, 

    day_of_year as datepart(dayofyear, [date]) persisted, 
    [week] as datepart(week, [date]), 

    day_name as datename(dw, [date]), 

    is_weekend as case when datepart(dw, [date]) = 7 or datepart(dw, [date]) = 1 then 1 else 0 end, 

    [quarter] as datepart(quarter, [date]) persisted 
    --etc...  

) 

--populate the calendar 

declare @date datetime 
set @date = '1-1-2000' 

while @date <= '12-31-2100' 
begin 

    insert Calendar select @date 
    set @date = dateadd(day, 1, @date) 

end 

然後,創建一個FiscalYear觀點:

create view FiscalYear 
as 
    select 

     id, 

     case when month = 11 or month = 12 then year + 1 else year end as [year] 


    from Calendar 

所以,當你需要一個給定日期的財年中,只使用類似下面的查詢:

select C.*, FY.year fiscal_year from Calendar C inner join FiscalYear FY on FY.id = C.id 

中當然,因爲會計年度只是一個列的計算,您也可以將其作爲日曆表本身的一部分。然後,它只是:

select * from Calendar 
0

如果您對2018年1月1日在10米不同的地方和邏輯改變了這種邏輯開始(說),你將有你的手一個爛攤子。

創建具有邏輯功能,然後使用類似功能:

SELECT InvoiceDate, dbo.FiscalPeriod(InvoiceDate) AS FP 
FROM ... 

喜歡的東西:

CREATE FUNCTION dbo.FiscalPeriod(@InvoiceDate DateTime) 
RETURNS int 
AS BEGIN 
    DECLARE @FiscalDate DateTime 

    SET @FiscalDate = DATEADD(month, 2, @InvoiceDate) 

    RETURN YEAR(@FiscalDate) * 100 + MONTH(@FiscalDate) 
END 

這將返回值像201705的,但你可以有dbo.FiscalPeriodMonth()和dbo.FiscalPeriodYear()如果你需要。您可以在一個地方根據需要設置複雜的邏輯。