简体   繁体   English

如何在 SQL Server 中获取上一季度的月份和年份

[英]How to get previous -previous quarters month and year in SQL Server

  • If the date is 2020-07-14, output month:3 year:2020如果日期为 2020-07-14,则输出月份:3 年:2020
    previous-previous quarter is 1 and 1st quarter last month is 3上一季度是 1,上个月第一季度是 3

  • If the date is 2020-03-14, output month:9 year:2019如果日期为 2020-03-14,则输出月:9 年:2019
    previous-previous quarter is 3 and 3rd quarter last month is 9上一季度是 3,上个月的第三季度是 9

Did this for Month:做了这个月:

declare @month int;
declare @quarter int

set @quarter= DATEPART(Quarter, '2020-10-14')
set @month = (@quarter - 2) *3

select @month
select @quarter

Please do help me with the year.请帮我过年。 I have searched online gone through Datediff and dateadd functions but it is confusing我在网上搜索过 Datediff 和 dateadd 函数,但它令人困惑

If it is the last day of the quarter then here is one solution.如果是本季度的最后一天,那么这里有一个解决方案。 This should work going forwards and backwards.这应该向前和向后工作。

DECLARE @ReportDate DATETIME = '2020-07-14'
DECLARE @QuarterInterval INT = -2

DECLARE @EndOfQuarter DATETIME =(SELECT DATEADD(DAY, -1, DATEADD(QUARTER, DATEDIFF(QUARTER, 0,DATEADD(QUARTER,@QuarterInterval , @ReportDate)) +1, 0)))

SELECT 
    TheDate = @EndOfQuarter,
    TheMonth = DATEPART(MONTH,@EndOfQuarter),
    TheYear = DATEPART(YEAR,@EndOfQuarter)

I think I'd find it easier to adjust the date to the first day of the final month of the current quarter then take 6 months off it:我想我会更容易将日期调整到当前季度最后一个月的第一天,然后再减去 6 个月:

declare @quart int;
declare @month int;
declare @thedate date;
set @thedate = '2020-07-14';
set @quart = DATEPART(quarter, @thedate);
set @month = ((@quart - 1) * 3) + 2
set @thedate = DATEFROMPARTS(@year, @month, 1)
set @thedate = DATEADD(month, @thedate, -6)

If it's the last day of the quarter before last quarter you can use the EOMONTH function to turn this date into the last day of the month rather than the first如果是上个季度之前的最后一天,您可以使用 EOMONTH 函数将此日期转换为该月的最后一天而不是第一天

You could also consider taking your current date, adding (((MONTH(date) - 1) % 3) - 6) months to it then EOMONTHing it.您还可以考虑采用当前日期,添加 (((MONTH(date) - 1) % 3) - 6) 个月然后 EOMONTHing 它。 The formula produces either -4, -5 or -6 depending on whether the month is the first second or third in the quarter (7th is the first month of q3, it becomes -4, and 7-4 = 3, March, the last month of q1).该公式产生 -4、-5 或 -6,具体取决于月份是该季度的第一个第二个还是第三个(7th 是 q3 的第一个月,它变为 -4,并且 7-4 = 3,3 月,第一季度的最后一个月)。 EOMONTH will put the date to last in the month at the end of the math EOMONTH 将把日期放在算术结束的月份

You can give this a try:你可以试试这个:

declare @month int;declare @edate date,@year int;
set @edate= dateadd(qq, DateDiff(qq, 0, Dateadd(Month,-6,'2020-07-14'))+1,-1)
set @month=month(@edate)
set @year=year(@edate)
select @month
select @year

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

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