MySQL Number of Days inside a DateRange, inside a month (Booking Table)

前端 未结 1 1860
遥遥无期
遥遥无期 2021-01-23 04:30

I\'m attempting to create a report for an accommodation service with the following information:

Number of Bookings (Easy, use the COUNT function)
Revenue Amount          


        
相关标签:
1条回答
  • 2021-01-23 05:18

    You're on the right lines. You need to join your query with a table of the months for which you want data, which can either be permanent or (as shown in my example below) created dynamically in a UNION subquery:

    SELECT   YEAR(month.d),
             MONTHNAME(month.d),
             SUM(1 + DATEDIFF( -- add 1 because start&finish on same day is still 1 day
               LEAST(Checkout, LAST_DAY(month.d)), GREATEST(Checkin, month.d)
             )) AS days
    FROM     bookingdata
      RIGHT JOIN (
                       SELECT 20110101 AS d
             UNION ALL SELECT 20110201 UNION ALL SELECT 20110301
             UNION ALL SELECT 20110401 UNION ALL SELECT 20110501
             UNION ALL SELECT 20110601 UNION ALL SELECT 20110701
             UNION ALL SELECT 20110801 UNION ALL SELECT 20110901
             UNION ALL SELECT 20111001 UNION ALL SELECT 20111101
             UNION ALL SELECT 20111201
      ) AS month ON
                 Checkin <= LAST_DAY(month.d)
             AND month.d <= Checkout
    GROUP BY month.d
    

    See it on sqlfiddle.

    0 讨论(0)
提交回复
热议问题