如何计算两个日期之间的天数,

时间:2014-07-08 06:18:40

标签: mysql sql date datediff

在MySQL中是否可以轻松地获取两个日期之间的天数,按月分组,然后在几个月之间分散这些天数,这样当我按月分组时,我会看到两个日期之间有多少天每个月有两个日期。

示例:创建05.05.2014到期06.06.2014返回32天。我希望将其显示为:

5月:26天 六月:5天

到目前为止,我已经:

SELECT MONTHNAME(date) as month_name,
SUM(DATEDIFF(expiration, date)) AS num_days
FROM reservations
GROUP BY month_name

但它并没有按月分散这些日子,显然是将它们全部放入逐个月组。任何想法都会受到高度关注。

1 个答案:

答案 0 :(得分:0)

我会先建立一个综合日期临时表(或CTE)。

从那里,您可以选择您喜欢的内容,然后根据您的需要对其进行分组。

    IF OBJECT_ID('TEMPDB..#Dates') IS NOT NULL DROP TABLE #Dates

    DECLARE @StartDate DATETIME, @EndDate DATETIME

        SET @StartDate = '05/05/2014'
        SET @EndDate = '06/06/2014'

    ;WITH Dates AS
        (
         SELECT CAST(CONVERT(VARCHAR(8), @StartDate,112) AS INT) AS DateId
              , CAST(@StartDate AS DATE) AS Date
              , CAST(@StartDate AS DATETIME) AS DateTime
              , DATEPART(QUARTER, @StartDate) AS QuarterId
              , 'Q' + CAST(DATEPART(QUARTER,@StartDate) AS CHAR(1)) AS Quarter
              , DATEPART(MONTH, @StartDate) AS MonthId
              , DATENAME(MONTH, @StartDate) AS Month
              , DATEPART(DAY, @StartDate) AS Day
              , DATEPART(YEAR, @StartDate) AS Year
              , DATENAME(DW,@StartDate) AS DayOfWeek
              , DATEPART(DAYOFYEAR, @StartDate) AS DayOfYear

          UNION ALL

         SELECT CAST(CONVERT(VARCHAR(8),DATEADD(DAY, 1, D.DateTime), 112) AS INT) ASDateId
              , CAST(DATEADD(DAY, 1, D.DateTime) AS DATE) AS Date
              , CAST(DATEADD(DAY, 1, D.DateTime) AS DATETIME) AS DateTime
              , DATEPART(QUARTER,DATEADD(DAY,1,D.DateTime)) AS QuarterId
              ,'Q'+CAST(DATEPART(QUARTER,DATEADD(DAY, 1, D.DateTime)) AS CHAR(1)) AS Quarter
              , DATEPART(MONTH,DATEADD(DAY, 1, D.DateTime)) AS MonthId
              , DATENAME(MONTH,DATEADD(DAY, 1,D.DateTime)) AS Month
              , DATEPART(DAY,DATEADD(DAY, 1, D.DateTime)) AS Day
              , DATEPART(YEAR,DATEADD(DAY, 1, D.DateTime)) AS Year
              , DATENAME(DW,DATEADD(DAY,1, D.DateTime)) AS DayOfWeek
              , DATEPART(DAYOFYEAR,DATEADD(DAY,1, D.DateTime)) AS DayOfYear
           FROM Dates AS D
          WHERE D.DateTime < @EndDate
        )

    SELECT DateId AS DateId
         , Date AS Date
         , DateTime AS DateTime
         , QuarterId AS QuarterId
         , Quarter AS Quarter
         , MonthId AS MonthId
         , Month AS Month
         , Day AS Day
         , Year AS Year
         , DayOfWeek AS DayOfWeek
         , DayOfYear AS DayOfYear
         , ROW_NUMBER() OVER(ORDER BY DateId)-1 AS DayCount
      INTO #Dates
      FROM Dates AS D
     ORDER BY D.DateId
    OPTION (MAXRECURSION 32767)

    -- SELECT * FROM #Dates

SELECT COUNT(Day) AS CountOfDays, Month
  FROM #Dates
  GROUP BY Month