{x}
blog image

The First Day of the Maximum Recorded Degree in Each City

Solution Explanation:

This problem requires finding the first day when the maximum temperature was recorded for each city. The solution uses a window function to efficiently achieve this.

Approach:

  1. Finding the Maximum Degree for Each City: We first need to determine the maximum temperature recorded for each city. This is done using a window function RANK() partitioned by city_id and ordered by degree (descending) and day (ascending). RANK() assigns the same rank to rows with the same maximum degree; the earliest date will have precedence because of the secondary ordering by day.

  2. Selecting the First Day: Once we have the ranks, we filter the result to select only the rows with rank 1. This represents the first day (earliest date) the maximum degree was recorded for each city.

  3. Ordering the Result: Finally, we order the result by city_id in ascending order as per the problem statement.

Time Complexity Analysis:

The time complexity of this solution is dominated by the RANK() window function. Window functions generally have a time complexity of O(N log N), where N is the number of rows in the Weather table. This is because sorting is often involved in the computation. The filtering and ordering steps have a linear time complexity O(N). Thus, the overall time complexity of the solution is O(N log N).

Code Explanation (MySQL):

WITH
    T AS (
        SELECT
            *,
            RANK() OVER (
                PARTITION BY city_id
                ORDER BY degree DESC, day
            ) AS rk
        FROM Weather
    )
SELECT city_id, day, degree
FROM T
WHERE rk = 1
ORDER BY 1;
  • WITH T AS (...): This is a Common Table Expression (CTE). It defines a temporary result set named T which is used in the main query.
  • *SELECT , RANK() OVER (...) AS rk: This selects all columns from the Weather table and adds a new column named rk (rank). The RANK() function partitions the data by city_id (meaning it calculates ranks separately for each city) and orders it by degree (descending) and then day (ascending). If multiple days have the same maximum degree, the earlier day gets a lower rank.
  • FROM Weather: This specifies the source table for the CTE.
  • SELECT city_id, day, degree FROM T WHERE rk = 1: This selects the city_id, day, and degree from the CTE T and filters the result to keep only rows where the rank (rk) is 1.
  • ORDER BY 1: This orders the final result set by the first column (city_id) in ascending order.

This SQL query effectively and efficiently solves the problem by leveraging the power of window functions. No other languages are explicitly requested, and the problem is inherently database-related making other languages less suitable.