Home > Software design >  COUNT function not counting correctly with DATEDIFF
COUNT function not counting correctly with DATEDIFF

Time:10-26

I am sure this is a simple fix, but can not figure it out. I have a COUNT function that needs to count the total number of Rentals. Alone, the function works just fine. I have tried using DISTINCT, tweaking the GROUP BY, and ORDER BY, but to not avail.

When I add the DATEDIFF function to get the NumberofDays rented, the COUNT function does not work the way as intended. I should be getting some results with "2" instead of "1". Note that I need to order by the Rentals.Boat_ID. Here is my code and table results. Thanks

SELECT
    BOATS.Boat_Brand,
    COUNT(RENTALS.Boat_ID) AS NumberofRentals,
    DATEDIFF(Day, RENTALS.Rental_StartDay, RENTALS.Rental_EndDay) 1) as NumberofDaysRented
FROM RENTALS
INNER JOIN BOATS
    ON RENTALS.Boat_ID = BOATS.Boat_ID 
GROUP BY
    BOATS.Boat_Brand,
    RENTALS.Rental_StartDay,
    RENTALS.Rental_EndDay
ORDER BY
    COUNT(RENTALS.Boat_ID) DESC;
Boat_Brand NumberofRentals NumberofDaysRented
Blue Martin 1 20
Blue Martin 1 35
Boston 1 52
Cherubini 1 11
Dufour 1 10
Eagle Craft 1 19
Motor Yacht 1 17
Motor Yacht 1 47
Grady-White 1 1
Horizon 1 22
Lemsteraak 1 19
Lund 1 64
Mastercraft 1 19
Mastercraft 1 1
Nauticat 1 10
Tracker 1 18
Tracker 1 1
Viking 1 20
Yamaha 1 20

EXPECTED TABLE/RESULTS:

Boat_Brand NumberofRentals NumberofDaysRented
Blue Martin 2 55
Motor Yacht 2 64
Mastercraft 2 20
Tracker 2 19
Boston 1 52
Cherubini 1 11
Dufour 1 10
Eagle Craft 1 19
Grady-White 1 1
Horizon 1 22
Lemsteraak 1 19
Lund 1 64
Nauticat 1 10
Viking 1 20
Yamaha 1 20

CodePudding user response:

seems like you need to group only by brand and get sum of rented days :

SELECT
    BOATS.Boat_Brand,
    COUNT(RENTALS.Boat_ID) AS NumberofRentals,
    SUM(DATEDIFF(Day,RENTALS.Rental_StartDay,RENTALS.Rental_EndDay)   1)) as NumberofDaysRented
FROM
    RENTALS
    INNER JOIN BOATS ON RENTALS.Boat_ID = BOATS.Boat_ID
GROUP BY
    BOATS.Boat_Brand
ORDER BY
    COUNT(RENTALS.Boat_ID) DESC;
  • Related