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

时间:2016-08-12 22:14:14

标签: sql sql-server

所以我有这个公式

n

我想创建一个名为data.frame(approx(df, n = nrow(df))) x y 1 1 10 2 2 15 3 3 20 4 4 14 5 5 8 6 6 2 的新公式,我希望它能产生相同的结果。

但不是写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 我想写dbo.GetPastQtr_fn,它会给我select dbo.FutureQtr_fn (20154,7) -> 20173

所以它会失败!

1 个答案:

答案 0 :(得分:0)

Select dbo.GetPastQtr_fn(20154,7)

返回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