SQL帮助-按季度汇总客户会计年度

时间:2019-10-07 21:53:55

标签: sql database azure-data-studio

我一直在这个问题上待了一段时间,目前我陷入困境:

Image Of Question With Example

这是我目前的尝试:

SQL Code

我只拍摄了代码的一小部分,因为一般的想法可以在少数case语句中理解。事实证明,这太混乱了,我认为他们的解决方案更简单。不一定需要答案,但是一些指导会有所帮助,因为我想自己尝试一下。谢谢!

1 个答案:

答案 0 :(得分:0)

您还在为此挣扎吗?

    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.

我希望这对您有帮助