Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在“年”和“月”字段中获取最近一年的记录_Sql_Sql Server_Sql Server 2008 - Fatal编程技术网

Sql 在“年”和“月”字段中获取最近一年的记录

Sql 在“年”和“月”字段中获取最近一年的记录,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我有一张这样的桌子: Id | Year | Month 1 | 2018 | 1 2 | 2018 | 2 3 | 2018 | 3 我需要选择最近12个月的ids,以下是我的想法: SELECT TOP 12 [Id], YEAR([DateReported]) AS [Year], MONTH([DateReported]) AS [Month] FROM ( SELECT [Id], CAST(CAST([Year] AS VARCHAR(10)) + '/' + CAS

我有一张这样的桌子:

Id | Year | Month
1  | 2018 | 1
2  | 2018 | 2
3  | 2018 | 3
我需要选择最近12个月的ids,以下是我的想法:

SELECT TOP 12 [Id],
YEAR([DateReported]) AS [Year], MONTH([DateReported]) AS [Month]
FROM (
    SELECT [Id], CAST(CAST([Year] AS VARCHAR(10)) + '/' + CAST([Month] AS VARCHAR(10)) + '/1' AS DATETIME) AS DateReported
    FROM [MyTable]
) T
ORDER BY T.[DateReported] DESC
然而,我做的演员太多了,有没有更有效的方法?

这个怎么样:

select t.*
from t
where year * 12 + month >= year(getdate()) * 12 + month(getdate()) * 12 - 12;
我会按月份排序(降序),然后我会得到前12行,如下所示:

select top 12 id
from my_table
order by year * 12 + month desc

看起来你不想要最近12个月的,你想要最近12个月(也就是一年)的。你根本不需要做任何铸造

declare @t table(id int identity(1,1), year int, month int);

insert into @t(year, month)
values (2017,11)
  ,(2017,11)
  ,(2017,12)
  ,(2017,12)
  ,(2018,1)
  ,(2018,2)
  ,(2018,1)

select *
from @t t
where format(t.year , '0000')+'-' +format(t.month, '00') >= format(dateadd(year, -1, getdate()), 'yyyy-MM')

假设Select返回正确的结果,则无需进行任何类型的计算,只需使用以下命令进行排序:

select top 12 Id, [year], [month]
from MyTable 
order by [year] desc, [month] desc

我不明白你在干什么。首先将两列(年/月)组合成一个日期,然后从中提取年/月?这应该会返回相同的结果:
按[year]desc从MyTable order中选择前12*,[month]desc
应该是
年*12+月
我知道我想得太多了,现在看到它,我没有想到它有点尴尬。