Tsql - >过滤数据从今天起6个月,表中的日期字段为YYYYMM

时间:2017-03-30 18:00:29

标签: tsql date

我需要一些帮助。 目前是2017年3月。 如何从2017年2月到今年年底前提取所有记录。我表格中的日期格式是YYYYMM

这是我的sql语句

+------------+-------+--------------+
| month_name | month | month_number |
+------------+-------+--------------+
| January    |     1 |       201601 |
| February   |     2 |       201602 |
| March      |     3 |       201603 |
| April      |     4 |       201604 |
| May        |     5 |       201605 |
| June       |     6 |       201606 |
| July       |     7 |       201607 |
| August     |     8 |       201608 |
| September  |     9 |       201609 |
| October    |    10 |       201610 |
| November   |    11 |       201611 |
| December   |    12 |       201612 |
| January    |     1 |       201701 |
| February   |     2 |       201702 |
| March      |     3 |       201703 |
| April      |     4 |       201704 |
| July       |     7 |       201707 |
| December   |    12 |       201712 |
+------------+-------+--------------+

我得到的输出如下:

git push origin origin/head:refs/tags/foo

我没有得到正确的输出。我仍然从2016年1月起获得数据。请帮忙

由于

2 个答案:

答案 0 :(得分:0)

 Select *
 From  Budget
 Where month_number>= convert(varchar(6),DATEADD(MONTH, -6, CURRENT_TIMESTAMP),112) 
 Order By month_number

如果是2012 +

Select *
 From  Budget
 Where month_number>=  format(DATEADD(MONTH, -6, CURRENT_TIMESTAMP),'yyyyMM') 
 Order By month_number

返回

month_name  month   month_number
September   9       201609
October     10      201610
November    11      201611
December    12      201612
January     1       201701
February    2       201702
March       3       201703
April       4       201704
July        7       201707
December    12      201712

答案 1 :(得分:0)

另外..

declare @budget table (month_Number int)

insert @budget (month_number)
select 201601
union all
select 201602
union all
select 201702
union all
select 201705
union all
select 201709


select * from @budget
where month_number >= (YEAR(DATEADD(MONTH, -6, CURRENT_TIMESTAMP)) * 100) +  MONTH(DATEADD(MONTH, -6, CURRENT_TIMESTAMP));