Leetcode Problem 1635. Hopper Company Queries I

1635. Hopper Company Queries I

Leetcode Solutions

Key approach of the solution

Algorithm

  1. Create a recursive CTE named Months that generates a sequence of numbers from 1 to 12, representing the months of the year.
  2. Create a CTE named Driver that selects driver_id and the month of joining from the Drivers table, filtering for drivers who joined on or before 2020.
  3. Create a CTE named Ride that selects the month and ride_id from the AcceptedRides table joined with the Rides table, filtering for rides requested in 2020.
  4. Perform a LEFT JOIN of the Driver CTE with the Months CTE on the condition that the month of joining is less than or equal to the current month.
  5. Perform a LEFT JOIN of the Ride CTE with the result of the previous join on the month.
  6. Use the COUNT DISTINCT function to calculate the number of active drivers and accepted rides for each month.
  7. Group the results by month and order by month in ascending order.
  8. Select the month, the count of active drivers, and the count of accepted rides in the final output.

erDiagram
    Drivers {
        int driver_id PK
        date join_date
    }

    Rides {
        int ride_id PK
        int user_id
        date requested_at
    }

    AcceptedRides {
        int ride_id PK
        int driver_id
        int ride_distance
        int ride_duration
    }

    Drivers ||--o{ Rides : requests
    Rides ||--o{ AcceptedRides : accepts

Alternative Approach: Conditional Joins with Sub DataFrames

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...