简体   繁体   English

获取具有不同月份开始和结束日期的月份名称

[英]Get month name with different month start and end dates

Getting the month for the current date is, obviously, straight forward, but I'm needing to get the month name with a different end date. 很显然,获取当前日期的月份很简单,但是我需要获取具有不同结束日期的月份名称。

I need to get the month name with the start date of the month being the first Thursday after the first Wednesday of the month and the end date of the month being the first Wednesday of the following month. 我需要获取月份名称,该月份的开始日期是该月的第一个星期三之后的第一个星期四,该月的结束日期是下个月的第一个星期三。 It's for an accounting thing, so I'm not going to argue with the spec! 这是用于会计的事情,因此我不会与规范争论!

eg for 2014, January would run from 9th Jan - 5th Feb, February would run from 6th February - 5th March, March would run from 6th March - 2nd April. 例如2014年,一月从1月9日至2月5日,二月从2月6日至3月5日,三月从3月6日至4月2日。

I would suggest that you create a table with your 'accounting months' in it, having a start date, end date and month name columns. 我建议您创建一个包含“会计月份”的表格,其中包含开始日期,结束日期和月份名称列。

You could then query this to find the row where your date is between the start and end dates and return the month name. 然后,您可以查询此内容以找到日期在开始日期和结束日期之间的行,并返回月份名称。 Putting this into a scalar function would then allow it to be reusable and relatively easily updated for next years months as well. 然后将其放入标量函数将使其可重复使用,并且在接下来的几个月中也将相对容易地进行更新。

I think, as per Paddy's answer , a lookup table is the simplest thing to do. 我认为,按照Paddy的回答 ,查找表是最简单的事情。 Here's one way to generate the rows for it: 这是为其生成行的一种方法:

; With Numbers(n) as (
    select 4 union all select 5
), Months as (
    select CONVERT(date,'20010104') as StartDt,CONVERT(date,'20010207') as EndDt,
           DATENAME(month,'20010103') as Month
    union all
    select DATEADD(week,n1.n,StartDt),DATEADD(week,n2.n,EndDt),
           DATENAME(month,DATEADD(week,n1.n,StartDt))
    from Months,Numbers n1,Numbers n2 --Old-skool join, just for once
    where DATEPART(day,DATEADD(week,n1.n,StartDt)) between 2 and 8 and
          DATEPART(day,DATEADD(week,n2.n,EndDt)) between 1 and 7 and
          StartDt < '21000101'
)
select * from Months option (maxrecursion 0)

(CW since this is effectively just an extension to Paddy's answer but I don't want to edit their answer, nor is it suitable for a comment (CW,因为这实际上只是对Paddy答案的扩展,但我不想编辑他们的答案,也不适合发表评论

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

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