我有一个这样的表:
Id | Year | Month
1 | 2018 | 1
2 | 2018 | 2
3 | 2018 | 3
我需要选择最近的12个月的ID,这是我想到的:
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
但是,我做的演员过多,有没有更有效的方法?
答案 0 :(得分:3)
假设您的Select返回正确的结果,则无需进行任何类型的计算,只需使用以下命令即可
select top 12 Id, [year], [month]
from MyTable
order by [year] desc, [month] desc
答案 1 :(得分:0)
如何?
select t.*
from t
where year * 12 + month >= year(getdate()) * 12 + month(getdate()) * 12 - 12;
答案 2 :(得分:0)
我将按月份排序(降序),然后得到前12行,如:
select top 12 id
from my_table
order by year * 12 + month desc
答案 3 :(得分:0)
看起来您不想要最近的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')