sqlserver:
select convert(varchar(7),dateadd(mm,-t.number,getdate()),120)
from
(select number from master..spt_values where type='P') t
where year(dateadd(mm,-t.number,getdate()))=year(getdate())
order by convert(varchar(7),dateadd(mm,-t.number,getdate()),120)
oracle:
select to_char(add_months(sysdate, -t.rn), 'yyyy-mm')
from dual a, (select rownum - 1 rn from dual connect by rownum <= 12) t
where to_char(add_months(sysdate, -t.rn), 'yyyy') =
to_char(sysdate, 'yyyy')
order by to_char(add_months(sysdate, -t.rn), 'yyyy-mm')
SQLServer版的写法:
SELECT left(convert(varchar(10),DATEADD(mm,DATEDIFF(mm,0,getdate()),0),120),7)YD into #YD
declare @Y int
set @Y=1
while @Y begin insert #YD select Left(convert(varchar(10),dateadd(month,-@Y,GETDATE()),120),7) set @Y=@Y+1 end select * from #YD order by YD
mysql> select DATE_FORMAT('1997-10-04 22:23:00', '%Y/%m ');
+----------------------------------------------+
| DATE_FORMAT('1997-10-04 22:23:00', '%Y/%m ') |
+----------------------------------------------+
| 1997/10 |
+----------------------------------------------+