-1

我们使用数据库中的查找表对周、月和年进行分组。可悲的是,创建它的小伙子早就走了,日历在年底就用完了!所以我真的需要找到一种方法来添加它!它设置有以下列:

在此处输入图像描述

老实说,我在 sql(MS2008) 方面不是很好,我对此感到很困惑,我们无法设置任何新的东西,因为一切都是围绕这个构建的!

4

1 回答 1

1

你可以这样做,但我不明白为什么你的日历从三月开始?

declare @Date_Start date, @Date_End date

select @Date_Start = '20130101'
select @Date_End = '20131231'

;with
CTE_Dates as (
    select @Date_Start as [Date]
    union all
    select dateadd(dd, 1, [Date])
    from CTE_Dates
    where [Date] < @Date_End
),
CTE_Calendar as (
    select
        [Date],
        datename(dw, [Date]) as [Day],
        datepart(ww, [Date]) as [Week],
        datepart(mm, [Date]) as [MonthID],
        dateadd(mm, datediff(mm, 0, getdate()), 0) as [Month],
        datepart(yy, [Date]) as [YearID],
        dateadd(yy, datediff(yy, 0, getdate()), 0) as [Year],
        datepart(qq, [Date]) as [QuarterID],
        dateadd(qq, datediff(qq, 0, getdate()), 0) as [Quarter]
    from CTE_Dates
)
select
    row_number() over (order by [Date]) + @Start_ID - 1 as ID,
    *
from CTE_Calendar
option (maxrecursion 0)

SQL 提琴示例

于 2013-07-01T14:16:55.357 回答