在StartDate和EndDate之间生成月份(SQL Server 2016)

时间:2018-11-13 21:01:51

标签: sql sql-server sql-server-2016

我有一个Customer表,我需要生成活动日期和非活动日期之间的月份。

这是原始数据:

Here's the raw data:

这是我希望得到的输出:

Here's the output I am hoping for:

谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用递归CTE:

    with yyyymm as (
      select customerid,
             datefromparts(year(activedate), month(activedate), 1) as dte,
             datefromparts(year(inactivedate), month(inactivedate), 1) as inactivemonth
      from Customer
      union all
      select customerid,
             dateadd(month, 1, dte),
             inactivemonth
      from yyyymm
      where dte < inactivemonth
     )
select CustomerId, year(dte) * 100 + month(dte)
from yyyymm
order by dte

这将结果作为月份的第一个日期。如果希望年/月值为字符串或数字,则可以适当地设置其格式。

答案 1 :(得分:0)

我对Gordon的脚本进行了一些更改(很抱歉,我也是新成员,我无法添加评论)。我相信这就是您想要的。

WITH Cus AS 
(
    select CustomerId   
            ,DATEFROMPARTS(YEAR(ActiveDate),MONTH(ActiveDate), 1) as ActiveDate
            ,DATEFROMPARTS(YEAR(InactiveDate),MONTH(InactiveDate), 1) as InactiveDate
    FROM Customer
) 
SELECT * 
FROM Cus C
INNER JOIN CustomerMonths CM ON C.CustomerId = CM.CustomerId
WHERE DATEFROMPARTS(LEFT(CM.MONTHS,4),RIGHT(CM.MONTHS,2),1) BETWEEN C.ActiveDate AND C.InactiveDate