如何在两个月之间按天分配收入

时间:2019-03-29 12:15:58

标签: sql sql-server

我们的系统中已将团体预订作为一个整体进行。我可以通过到达和离开的日期获得每个组在该区块上持有的总收入。 问题在于,每组的收入是所显示的总收入,是在整个卧室被封锁期间产生的收入。如果每个小组都在同一个月到达并离开,那就可以了。但是,有些小组会在一个月内到达,然后在下个月离开。 我需要按月划分这些组的收入。因此,例如,如果某个小组在28/06到达而在3/07离开,我需要知道6月(3个晚上)产生了多少收入,7月(2个晚上)产生了多少收入。 下面的查询是正确的,但是会根据EndDate(退房日期)给我总收入,因此收入将全部在小组离开的月份开始。 我也在比较去年的同一时间

SELECT DAILYREV = ProjectedRevenueAccomNett/ DATEDIFF(Day,BeginDate, EndDate), DATEDIFF(DAY,BeginDate, EndDate) AS StayNights, Year(BeginDate) ArrivalYear, GroupRef, GAStatus, SourceSiteId, BeginDate, EndDate, CreatedTimestamp, DefMarketSegmentCode,ProjectedRevenueAccomNett, ProjectedRevenueFBNett

From SyncGroupRoomBlockHeaders
WHERE  CreatedTimestamp <= '2019-03-28' 
  AND  BeginDate BETWEEN '2019-03-28' AND '2019-12-31'
or
  CreatedTimestamp <= '2018-03-28' 
  AND  BeginDate BETWEEN '2018-03-28' AND '2018-12-31'


  Order By YEAR (BeginDate)

1 个答案:

答案 0 :(得分:0)

您的问题可以用不同的方式解释。我认为以下查询将为您指明正确的方向。也许您可以使用此方法并根据自己的需要对其进行编辑:

USE TEMPDB

IF OBJECT_ID ('TEMPDB..Bookings') IS NOT NULL DROP TABLE Bookings;
CREATE TABLE Bookings (ID INT, 
                   StartDate DATE, 
                   EndDate Date, 
                   Total DECIMAL (8,2), 
                   NumberDays AS DATEDIFF (DAY, StartDate, EndDate))
INSERT INTO Bookings VALUES (1, '20190130', '20190202', 210.15)

IF OBJECT_ID ('TEMPDB..BookingNew') IS NOT NULL DROP TABLE BookingNew;
SELECT *, Total / NumberDays AS PricePerDay 
INTO BookingNew
FROM Bookings



DECLARE @StartDate DATE
DECLARE @EndDate DATE

SET @StartDate = '2000-01-01' -- <<  user input >>
SET @EndDate  = '2040-12-31'  -- <<  user input >>

IF OBJECT_ID ('TEMPDB..#Date') IS NOT NULL DROP TABLE #Date
IF OBJECT_ID ('TEMPDB..#Date') IS NULL CREATE TABLE #Date (Date DATE)

INSERT INTO #Date VALUES (@StartDate)

WHILE @StartDate < @EndDate

BEGIN
INSERT INTO #Date

SELECT DATEADD (DD, 1, @StartDate) AS Date

SET @StartDate = DATEADD (DD, 1, @StartDate)

END

SELECT * 
FROM #Date AS D
INNER JOIN BookingNew AS B ON D.Date BETWEEN B.StartDate AND B.EndDate