简体   繁体   English

需要一个公式来查找SQL中的年份和季度

[英]Need a formula to find year and quarter in SQL

So I have this formula 所以我有这个公式

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- This function takes a qtr (yyyyq), and adds the number of qtrs, and returns the future qtr
--e.g. FutureQtr (20154,7) returns 20173


CREATE FUNCTION [dbo].[FutureQtr_fn] (@StartQtr int,@AddlQtrs int)

Returns int

AS BEGIN

RETURN

      (@StartQtr/10*10)+ -- Current Year (yyyy)

            ((@StartQtr%(@StartQtr/10*10) +@AddlQtrs - 1)/4)*10 -- add'l years (n0)
            +(@StartQtr%(@StartQtr/10*10) +@AddlQtrs-1)%4  + 1 -- new qtr (n)

END
GO

I want to create a new formula called dbo.GetPastQtr_fn and I want it to produce the same result. 我想创建一个名为dbo.GetPastQtr_fn的新公式,并希望它产生相同的结果。

But instead of writing select dbo.FutureQtr_fn (20154,7) -> 20173 I want to write dbo.GetPastQtr_fn (20154,7) that will give me 20141 . 但是我没有写select dbo.FutureQtr_fn (20154,7) -> 20173而是想写dbo.GetPastQtr_fn (20154,7) ,这会给我20141

So it goes down! 所以它下降了!

Select dbo.GetPastQtr_fn(20154,7)

Returns 20141 返回20141

CREATE FUNCTION [dbo].[GetPastQtr_fn] (@StartQtr int,@AddlQtrs int)

Returns int

AS 

BEGIN
    Declare @Date Date=DateAdd(QQ,@AddlQtrs*-1,DateFromParts(@StartQtr/10,((@StartQtr-((@StartQtr/10)*10))*3),1))
    Return Year(@Date)*10+DatePart(QQ,@Date)
End

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM