你还在为这个苦苦挣扎吗?
Create function fiscalYearSummary (@OrderDate Date, @StartFiscalYearFromGivenMonth int)
returns nvarchar(20)as
begin
declare @MonthOfYear int
declare @Quarter int
set @MonthOfYear = datepart(MONTH, @OrderDate)
set @Quarter = (((((@MonthOfYear - (@StartFiscalYearFromGivenMonth )) + 12) % 12) + 1) / 4) + 1
return case @Quarter when 1 then 'Quarter I' when 2 then 'Quarter II' when 3 then 'Quarter III' when 4 then 'Quarter IV' else 'Error' end
end
这将用于选择
select dbo.fiscalYearSummary('20190101',1) -- January with the first month of the fiscal year January.
select dbo.fiscalYearSummary('20190401',4) -- April with the first month of the fiscal year April.
select dbo.fiscalYearSummary('20191231',1) -- December with the first month of the fiscal year January
我相信它可以做得更好,但这应该让你开始。
I get the Month from the passed in date (1 to 12)
Subtract @StartFiscalYearFromGivenMonth to drag it back by that many months.
Add 12 (a year) to make it positive, mod it with 12 to get it in the range 0 to 11, then add 1 to make that 1 to 12.
I divide the result by 4 to get the quarter - 0 to 3, then add 1 again, into range 1 to 4.
then a simple case returns the quarter.
我希望这有帮助