Leetcode Problem 2292. Products With Three or More Orders in Two Consecutive Years

2292. Products With Three or More Orders in Two Consecutive Years

Leetcode Solutions

Using Common Table Expressions (CTEs) and Window Functions

  1. Create a CTE named yearly_orders that selects product_id, the year of purchase_date, and the count of order_id for each product and year combination.
  2. Use the HAVING clause to filter only those combinations where the count of order_id is greater than or equal to 3.
  3. In the main query, select product_id from the CTE.
  4. Use the LEAD window function to get the next year for each product, partitioned by product_id and ordered by year.
  5. In the WHERE clause, check if the next year is exactly one year greater than the current year.
  6. Use DISTINCT to ensure each product_id is listed only once in the final result.

erDiagram
    Orders {
        int order_id PK
        int product_id
        int quantity
        date purchase_date
    }

Using Self-Join on Aggregated Subquery

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...