1

我们目前在仓库中有这个日期视图:

ALTER VIEW [dbo].[vw_DimDate] AS
SELECT
    D.DateKey
    , D.DayMarker AS DayMarker
    , D.Year_YYYY as CalendarYear
    , D.Quarter_QQ as QuarterName
    , D.Quarter_QQ + ' - ' + D.Year_YYYY AS CalendarQuarterName
    , D.Month_MMM as MonthShortName
    , D.Month_MMMM as MonthName
    , D.Month_MMMM + ' ' + D.Year_YYYY AS CalendarMonthName
    , D.Week_WW as WeekName
    , D.Week_WW + ' - ' + D.Year_YYYY AS CalendarWeekName
    , D.Day_DD + ' ' + D.Month_MMMM + ' ' + D.Year_YYYY AS CalendarDayName
    , D.DayOfWeekName
    ,convert(datetime,'01 ' + Month_MMM + ' ' + D.Year_YYYY) as FirstDayOfMonth
    --<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<as LastDayOfMonth 
    , W.WeekYear_YYYY as Week_Year
    , W.Week_WW + ' ' + W.WeekYear_YYYY as Week_YearWeekName
FROM
    WHData..TB_DimDate D
JOIN
    WHData..tb_DimDateWeek W
    on D.DateKey = W.DateKey
where
    D.DateKey < convert(char(8),getdate(),112)

我想添加一个字段LastDayOfMonth- 这个的标准实现是什么?

4

4 回答 4

1

最简单的方法是添加 1 个月,然后在 FirstDayOfMonth 中添加“-1”天。

于 2013-02-01T10:59:03.153 回答
1

要获取本月的最后一天,您可以使用:

DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, GETDATE())+1, 0))

请参阅SQL Fiddle with Demo

如果您的表中有日期列,那么您将替换GetDate()为您的列。从您当前的查询来看,它看起来是DateKey,所以您可以使用:

DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, D.DateKey)+1, 0))

请参阅带有演示的 SQL Fiddle

于 2013-02-01T11:00:26.557 回答
1

假设D.Year_YYYY&Month_MMM是字符串类型

dateadd(day,-1,dateadd(month, 1, D.Year_YYYY + right('0'+ Month_MMM,2) + '01'))
                                                             as LastDayOfMonth

此外,最好在转换为之前更改FirstDayOfMonthISO format

convert(datetime,D.Year_YYYY + right('0'+ Month_MMM,2) + '01') as FirstDayOfMonth
于 2013-02-01T11:32:06.073 回答
1

另一种选择

DATEADD(dd , - DAY([Date]), DATEADD(MONTH , 1, [Date]))

SQLFiddle上的演示

于 2013-02-01T16:27:53.707 回答