Write a SQL query that returns each customer ID and the total number of orders they placed in the year 2025, but only for customers who placed more than five orders.
π‘ Model Answer
You can achieve this with a simple GROUP BY and HAVING clause. Assuming the table is named Orders and has columns customer_id and order_date, the query would be:
SELECT customer_id,
COUNT(*) AS total_ordersFROM Orders
WHERE YEAR(order_date) = 2025
GROUP BY customer_id
HAVING COUNT(*) > 5;
This counts all rows per customer for 2025, then filters out those with five or fewer orders. The complexity is O(n) where n is the number of rows in the Orders table. If the database supports DATE_TRUNC or similar functions, you could replace YEAR(order_date) with DATE_TRUNC('year', order_date) = DATE '2025-01-01' for better portability.
This answer was generated by AI for study purposes. Use it as a starting point β personalize it with your own experience.
π€ Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers β invisible to screen sharing.
Get Assisting AI β Starts at βΉ500