如何使用当前时间选择过去12个月的名称。不使用任何表格 如果当前月份是十月,那么我希望结果为
month year
oct 2011
nov 2011
dec 2011
jan 2012
feb 2012
mar 2012
apr 2012
may 2012
jun 2012
jul 2012
aug 2012
sep 2012
oct 2012
我在数据库中没有任何表格。
答案 0 :(得分:12)
SET LANGUAGE English;
WITH R(N) AS
(
SELECT 0
UNION ALL
SELECT N+1
FROM R
WHERE N < 12
)
SELECT LEFT(DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE())),3) AS [month],
DATEPART(YEAR,DATEADD(MONTH,-N,GETDATE())) AS [year]
FROM R
答案 1 :(得分:5)
declare @start DATE = '2011-10-01';
with CTEE(date)
AS
(
SELECT @start
UNION all
SELECT DATEADD(month,-1,date)
from CTEE
where DATEADD(month,-1,date)>=DATEADD(month,-10,@start)
)
select Datename(month,date) from CTEE
答案 2 :(得分:2)
SELECT STR(MONTH(DATEADD(mm, number, GETDATE())), 2) AS MonthNum,
DATENAME(month, DATEADD(month, MONTH(DATEADD(mm, number, GETDATE())), 0) - 1) AS MonthNames
FROM master.dbo.spt_values
WHERE (name IS NULL) AND (number BETWEEN 0 AND 11)
答案 3 :(得分:0)
使用MVJ的F_TABLE_DATE: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=61519