计算日期之后每个月的天数

时间:2019-06-10 21:30:05

标签: sql sql-server

我试图查看是否可以计算出给定日期后一定天数的每个月中的天数。

例如,我的约会日期为2019-09-25。如果我计划接下来的105天,那么那几天是9月,10月,11月,依此类推?

Declare @dtdate date = '20190925',
@days int= 105

Select 
datediff(dd,@dtdate,eomonth(@dtdate)) as DaysSeptember
,datediff(dd,eomonth(@dtdate),eomonth(dateadd(m,1,@dtdate))) as DaysOctober

3 个答案:

答案 0 :(得分:3)

在我看来像Sql server。您只需简单地计算每个月的天数即可。这样做具有灵活性的优势。您只需更改@dtdate, @days,尽管月数有所更改,查询仍将有效。

DECLARE @dtdate date = '20190925', 
@days int= 105
,@dtmax date;
set @dtmax = dateadd(day, @days, @dtdate);

WITH cte AS (
  SELECT DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY 1/0), @dtdate) AS d
  FROM sys.objects s, sys.objects s2
)
select
    year(d) as year, datename(month, d) as month, count(*) as NumberOfDays
from cte
where d between @dtdate and @dtmax
group by year(d), datename(month, d)
order  by year(d), month

结果:

year    month   NumberOfDays
2019    December    31
2019    November    30
2019    October     31
2019    September   5
2020    January     8

答案 1 :(得分:0)

在Postgresql中,我会这样做的

SELECT date_part('month', d), count(d)
FROM generate_series('2019-09-25'::date, '2019-09-25'::date + INTERVAL '105 days', INTERVAL '1 day') series (d)
GROUP BY date_part('year',d), date_part('month', d)
ORDER BY date_part('year',d), date_part('month', d)

很明显,您没有使用postgresql,但这也许会给您提示。诀窍是在可以计数的间隔内创建一系列日期。这是带有月份和天数的输出。请注意有106天,因为该间隔包括开始日期和结束日期。

9;6
10;31
11;30
12;31
1;8

答案 2 :(得分:0)

也许不是最好的解决方案(不是基于集合的),而是一种替代方法:

DECLARE @dtdate      DATE = '20190925'
       ,@days        INT  = 105
       ,@DaysInMonth INT

DECLARE @results TABLE
    (
        ResultsID   INT        NOT NULL IDENTITY PRIMARY KEY
       ,YearMonth   VARCHAR(7) NOT NULL
       ,DaysInMonth INT        NOT NULL
    )


WHILE @days > 0
    BEGIN
        SET @DaysInMonth = DATEDIFF(dd, @dtdate, EOMONTH(@dtdate))
        SET @DaysInMonth = IIF(@days > @DaysInMonth, @DaysInMonth, @days)

        INSERT INTO @results
            (
                YearMonth
               ,DaysInMonth
            )
        SELECT  CONVERT(VARCHAR(7), @dtdate, 120)
               ,@DaysInMonth

        SET @days -= @DaysInMonth
        SET @dtdate = DATEADD(dd, 1, EOMONTH(@dtdate))
    END


SELECT  *
FROM    @results AS r