我有数据,我试图按自定义的季度间隔进行分组。数据是每日和UTC时间。我可以很容易地按月分解,但我很难在季度级别做到这一点。例如,财务日期需要从2017年3月22日开始,运行3个月。因此,该季度应该是3/22 / 17-6 / 22/17,并且也可以拉动所有其他月份。
我将这段代码用于月份级别:
CASE WHEN
CAST(DATEADD(HOUR, -4, c.dateUTC) AS DATE) BETWEEN DATEFROMPARTS(DATEPART(YEAR, DATEADD(MONTH, -1, CAST(DATEADD(HOUR, -4, c.dateutc) AS DATE))), DATEPART(MONTH, DATEADD(MONTH, -1, CAST(DATEADD(HOUR, -4, c.dateUTC) AS DATE))), 22)
AND DATEFROMPARTS(DATEPART(YEAR, CAST(DATEADD(HOUR, -4, c.dateUTC) AS DATE)), DATEPART(MONTH, CAST(DATEADD(HOUR, -4, c.dateUTC) AS DATE)), 21)
THEN DATENAME(MONTH, CAST(DATEADD(HOUR, -4, c.dateUTC) AS DATE)) + ' ' + CAST(DATEPART(YEAR, CAST(DATEADD(HOUR, -4, c.dateUTC) AS DATE)) AS VARCHAR(4))
WHEN CAST(DATEADD(HOUR, -4, c.dateUTC) AS DATE) > DATEFROMPARTS(DATEPART(YEAR, CAST(DATEADD(HOUR, -4, c.dateUTC) AS DATE)), DATEPART(MONTH, CAST(DATEADD(HOUR, -4, c.dateUTC) AS DATE)), 21)
THEN DATENAME(MONTH, DATEADD(MONTH, 1, CAST(DATEADD(HOUR, -4, c.dateUTC) AS DATE))) + ' ' + CAST(DATEPART(YEAR, DATEADD(MONTH, 1, CAST(DATEADD(HOUR, -4, c.dateUTC) AS DATE))) AS VARCHAR(4))
END AS FiscalMonth
但很难修改为具有正确的日期和代码的季度。是否有一个简单的修复方法可以将现有查询更改为季度级别。
答案 0 :(得分:0)
这可能有用,这个想法只是将输入日期转换为从1月1日开始的标准化比例。仅从发布的语法我假设SQL Server,但您应该添加RDBMS标记。
离。
SELECT '2017-03-22' AS Custom_strt,
inputDate,
DATEADD
( day,
DATEDIFF(day, Custom_strt, Q1_strt),
DATEADD(year, DATEDIFF(year,Q1_strt, inputDate), inputDate)
) AS normalizedDate,
DATE '2017-01-01' AS Q1_strt,
DATEADD(month, 3, Q1_strt) AS Q1_end,
DATEADD(day, 1, Q1_end) AS Q2_strt,
...
DATEADD(month, 3, Q4_strt) AS Q4_end,
CASE WHEN normalizedDate BETWEEN Q1_strt AND Q1_end THEN 'Q1'
WHEN normalizedDate BETWEEN Q2_strt AND Q2_end THEN 'Q2'
WHEN normalizedDate BETWEEN Q3_strt AND Q3_end THEN 'Q3'
WHEN normalizedDate BETWEEN Q4_strt AND Q1_end THEN 'Q4'
END AS fiscal_quarter
FROM SomeTable