2007-03-12

Simple query

A few days ago we sat down with my cousin to write a simple query on his database.
"Very simple" he said. "Just two or three lines" said I.
Please enjoy the clipped version:

DECLARE @dateMin DATETIME, @dateMax DATETIME

-- Give values

DECLARE @noOfDays DECIMAL(18,2)

SET @noOfDays = DATEDIFF(DAY, @dateMin, @dateMax)

SELECT [VW_RoomDetails].[Name] [Room], [RoomType], [OccupancyCount], [Charges], [TotalCharges], [TVA], (CASE WHEN ISNULL([OccupancyCount], 0.00) = 0 THEN 0 ELSE ISNULL([Charges], 0.00)/ISNULL([OccupancyCount],0.00) END) [ADR_Net],

(CASE WHEN ISNULL([OccupancyCount], 0.00) = 0 THEN 0 ELSE ISNULL([TotalCharges], 0.00)/ISNULL([OccupancyCount],0.00) END) [ADR_Brut], ISNULL([OccupancyCount], 0.00) / ISNULL(@noOfDays,0.00) *100 [OccupancyPercent]

FROM

VW_RoomDetails

LEFT JOIN

(
SELECT [ID_Room],

SUM (DATEDIFF(DAY, (CASE WHEN [CheckInDate] > @dateMin THEN [CheckInDate] ELSE @dateMin END),

(CASE WHEN [CheckOutDate] < @dateMax THEN [CheckOutDate] ELSE @dateMax END))) [OccupancyCount]

FROM [VW_RoomStayInfoDetails]

WHERE [StayType] = 1 AND

(([CheckInDate] >= @dateMin AND [CheckOutDate] <= @dateMax)

OR ([CheckInDate] <= @dateMin AND [CheckOutDate] >= @dateMin)

OR ([CheckOutDate] <= @dateMax AND [CheckOutDate] >= @dateMax)

OR [CheckInDate] <= @dateMin AND [CheckOutDate] > @dateMax )

GROUP BY [ID_Room]) [rooms]

ON VW_RoomDetails.ID_Room = rooms.ID_Room


LEFT JOIN
(
SELECT [ID_Room], SUM([Amount]) [Charges], SUM([Amount] + [TVA]) [TotalCharges], SUM ([TVA]) [TVA] FROM [TBL_Charge]
GROUP BY [ID_Room]
) [charges]

ON [rooms].[ID_Room] = [charges].[ID_Room]


1 comment:

Anonymous said...

Megjegyzem, hogy az effajta lekerdezeseknek van egyszerubb megoldasa is...