从当前月份获取前12个月的名称/ ID

时间:2014-01-15 09:02:18

标签: sql sql-server tsql

任何人都可以帮我从当前日期(月)获取最近12个月的名字。 我希望在sql server中进行此查询。

3 个答案:

答案 0 :(得分:3)

需要sql-server 2008

select datename(m,dateadd(m,-a,current_timestamp)) monthname,
       datepart(m,dateadd(m,-a,current_timestamp)) id
from (values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) x(a)

结果:

monthname  id
December   12
November   11
October    10
September   9
August      8
July        7
June        6
May         5
April       4
March       3
February    2
January     1

答案 1 :(得分:3)

您可以为解决方案使用公用表表达式:

;WITH DateRange AS(
    SELECT GETDATE() Months
    UNION ALL
    SELECT DATEADD(mm, -1, Months)
    FROM   DateRange

    WHERE Months > DATEADD(mm, -11, GETDATE())
)

SELECT DateName(m, Months) AS Months, Month(Months) AS ID FROM DateRange

显示订单中的前几个月:

    Months                         ID
------------------------------ -----------
January                        1
December                       12
November                       11
October                        10
September                      9
August                         8
July                           7
June                           6
May                            5
April                          4
March                          3
February                       2

答案 2 :(得分:0)

为什么不是简单的获取日期?

SELECT name FROM [yourtable] WHERE
[tabledate] >= DATEADD(month, -12, GETDATE())
这是什么意思?

另外,如果这是您需要的解决方案,Google周围有很多示例可以快速搜索。这是常见的陈述。