从用户定义开始的月份

时间:2017-12-11 11:29:55

标签: sql-server tsql

enter image description here

要求说每个月从22日开始到下个月21日结束。

我们公司月份从每月22日开始,月份的最后一天是21日,所以我需要计算一下几个月

for example 
date                              output
22nd Oct 2017 to 21st Nov 2017 =  Nov 2017
22nd Nov 2017 to 21st Dec 2017 =  Dec 2017
22nd Dec 2017 to 21st Jan 2018 =  Jan 2018
22nd Jan 2018 to 21st Feb 2018 =  Feb 2018

所以当我运行查询时,它会查看日期并给我一年的名字

1 个答案:

答案 0 :(得分:0)

根据你的评论改变了我的答案。

请亲自尝试代码:http://sqlfiddle.com/#!6/4b3e5/5

declare @MyTable table (MyDate datetime)

insert into @MyTable (MyDate) 
values ('20171022'), ('20171121'), ('20171122'), ('20171221'), ('20171222'), ('20180121'), ('20180221')

select t.MyDate,
       case when datepart(day, t.MyDate) > 21 then datename(month, dateadd(month, 1, t.MyDate)) + ' ' + datename(year, dateadd(month, 1, t.MyDate))
            else datename(month, t.MyDate) + ' ' + datename(year, t.MyDate)
       end
from   @MyTable t

结果现在是

MyDate      | COLUMN1   
------------|--------------
22/10/2017  | November 2017 
21/11/2017  | November 2017 
22/11/2017  | December 2017 
21/12/2017  | December 2017 
22/12/2017  | January 2018  
21/01/2018  | January 2018  
21/02/2018  | February 2018

如果您只需要从月份开始的前3个字符,请使用子字符串来获取它们

select t.MyDate,
       case when datepart(day, t.MyDate) > 21 then substring(datename(month, dateadd(month, 1, t.MyDate)), 1, 3) + ' ' + datename(year, dateadd(month, 1, t.MyDate))
            else substring(datename(month, t.MyDate), 1, 3) + ' ' + datename(year, t.MyDate)
       end
from   @MyTable t

现在结果是

MyDate      | COLUMN1   
------------|--------------
22/10/2017  | Nov 2017  
21/11/2017  | Nov 2017  
22/11/2017  | Dec 2017  
21/12/2017  | Dec 2017  
22/12/2017  | Jan 2018  
21/01/2018  | Jan 2018  
21/02/2018  | Feb 2018