Question

I am working with an equipment reservation system and need to calculate days that the equipment is being rented for so I can multiply it by the total cost per day of each reservation, then total the cost for all reservations in the query. The equipment pickup date and return date are stored in separate fields as yyyy/mm/dd 00:00:00.000 (no entries contain a time other than 00:00:00.000), there is also fields for pickup AM/PM and return AM/PM. If the pickup date is in the PM then that day does not count as a day, if the return date is in the AM then it does not count as a day. Ideally I would like to use the query below to get to my end goal, however it calculates the number of days as too many.

SELECT
    SUM(TOTAL*DATEDIFF(day,PICKUPDT,RETURNDT)) 
FROM
    RENTAL 
WHERE
    AGENTCODE = '$AGENT' AND
    PICKUPDT >= '06/01/2013' AND
    RETURNDT <= '06/01/2014' AND
    PAIDOUT = '1' )

The above is nested within the whole query that I am running. The TOTAL field is the cost per day of rental. I need a way to accurately count the number of days the consumer will be charged for. I appreciate any help that can be given on the topic. This is my first question here and apologize in for any mistakes I made.

The finished screen I am working towards can be seen here:

http://jeffreyalanscott.com/stack_overflow1.jpg

No correct solution

OTHER TIPS

I would suggest using TIMESTAMPDIFF instead of DATEDIFF as DATEDIFF only considers the date components and not the time.

SELECT SUM(total * TIMESTAMPDIFF(DAY, pickupdt, returndt) + 1)
...

For example:

SELECT TIMESTAMPDIFF(DAY, '2014-01-01 08:00:00', '2014-01-02 12:00:00') + 1;

would yield an integer value of 2 indicating that the item was check out for longer than 24 hours.

The + 1 part is because the function rounds down partial days.

You can use a case statement to increment the day count based on the hour-of-day of the return time. You might implement more granular rules based on the Days:Hours:

declare @rental table (AgentCode varchar(100), PickUpDt datetime, ReturnDt datetime, PickupAmPm char(2), ReturnAmPm char(2));

insert into @rental
    select '123', '2014-02-01', '2014-02-02', 'AM', 'PM' union all
    select '456', '2014-02-01', '2014-02-02', 'AM', 'AM'



select  AgentCode, 
        [total] = datediff(dd, PickupDt, ReturnDt) + case ReturnAmPm when 'AM' then 0 else 1 end
from @rental

Returns:

AgentCode   total       
----------- ----------- 
123         2           
456         1           
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top