【问题标题】:How to calculate StartDate and EndDate based on ReportingMonth value如何根据 ReportingMonth 值计算 StartDate 和 EndDate
【发布时间】:2018-11-16 19:46:12
【问题描述】:

我需要根据 ReportingMonth 值计算 StartDate 和 EndDate

样本数据:

CREATE TABLE TestDate (
    [ID] [int] NULL,
    [PerID] [int] NULL,
    [CommID] [int] NULL,
    [ReportingMonth] [nvarchar](200) NULL,
    [Number] [nvarchar](200) NULL
)

Insert into TestDate ( [ID],[PerID],[CommID],[ReportingMonth],[Number])
    Values ('3820','12508','7','Jul-16','31');
Insert into TestDate ( [ID],[PerID],[CommID],[ReportingMonth],[Number])
    Values ('10235','12498','58','Aug-16','1');
Insert into TestDate ( [ID],[PerID],[CommID],[ReportingMonth],[Number])
    Values ('10235','12498','2','Jul-16','15');

我需要根据 ReportingMonth 计算 StartDate 和 EndDate 与 Number 列的差异

StartDate 和 EndDate 的预期输出应该是这样的

ID  PerID   CommID  ReportingMonth  StartDate   Number  EndDate
3820    12508   7   Jul-16          30/06/2016  31      31/07/2016
10235   12498   58  Aug-16          15/07/2016  1       1/08/2016
10235   12498   2   Jul-16          15/07/2016  15      1/08/2016

我用来计算一个月开始日期的 SQL 查询正在运行,但是当有多个相同的 ID 时,它就不起作用了

select [ID]
       ,[PerID]
       ,[CommID]
       ,[ReportingMonth]
       ,[Number]
       ,DATEADD(DAY, -(cast([Number] as int)), eomonth(CAST([Number] as DateTime)))  as StartDate
    from TestDate

如何在只有 ReportingMonth 字段的基础上获取 StartDate 和 EndDate

谢谢, 桑迪普

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    SQL Server 在计算月份转换方面非常出色。所以,这应该工作:

    select cast('01-' + ReportingMonth as date) as month_start,
           eomonth(cast('01-' + ReportingMonth as date)) as month_end
    

    【讨论】:

    • 我需要根据 [ReportingMonth] 和 [Number] 的差异计算 StartDate 和 Enddate。您可以在原始线程中看到预期的输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    相关资源
    最近更新 更多