Calculate Orders Within Each Interval - Problem

You are given a table Orders that contains order counts for specific minutes.

Each row contains a minute and the number of orders received during that minute. The total number of rows will always be a multiple of 6.

Write a query to calculate total orders within each interval. Each interval is defined as a combination of 6 consecutive minutes:

  • Minutes 1-6 fall within interval 1
  • Minutes 7-12 fall within interval 2
  • And so forth...

Return the result table ordered by interval_no in ascending order.

Table Schema

Orders
Column Name Type Description
minute PK int The minute number (primary key)
order_count int Number of orders received during that minute
Primary Key: minute
Note: Each row represents order count for a specific minute. Total rows is always a multiple of 6.

Input & Output

Example 1 — Basic Interval Calculation
Input Table:
minute order_count
1 2
2 11
3 15
4 0
5 0
6 0
7 1
8 0
9 0
10 0
11 0
12 0
Output:
interval_no total_orders
1 28
2 1
💡 Note:

Minutes 1-6 form interval 1 with total orders: 2+11+15+0+0+0 = 28. Minutes 7-12 form interval 2 with total orders: 1+0+0+0+0+0 = 1.

Example 2 — Multiple Intervals
Input Table:
minute order_count
1 5
2 3
3 2
4 1
5 4
6 0
7 10
8 8
9 6
10 4
11 2
12 0
Output:
interval_no total_orders
1 15
2 30
💡 Note:

Interval 1 (minutes 1-6): 5+3+2+1+4+0 = 15 orders. Interval 2 (minutes 7-12): 10+8+6+4+2+0 = 30 orders.

Constraints

  • 1 ≤ minute ≤ 1000
  • 0 ≤ order_count ≤ 1000
  • The total number of rows is always a multiple of 6

Visualization

Tap to expand
Calculate Orders Within Each Interval INPUT: Orders Table minute order_count 1 15 3 20 6 10 8 25 11 30 14 18 Intervals (6 mins each): 1-6 = Interval 1 7-12 = Interval 2 13-18 = Interval 3 ALGORITHM STEPS 1 Calculate Interval CEIL(minute / 6) minute 8 --> CEIL(8/6)=2 2 Group by Interval GROUP BY interval_no Int 1: mins 1,3,6 Int 2: mins 8,11 3 Sum Orders SUM(order_count) Int 1: 15+20+10 = 45 Int 2: 25+30 = 55 4 Order Result ORDER BY interval_no ASC: 1, 2, 3... FINAL RESULT interval_no total 1 45 2 55 3 18 SQL Query SELECT CEIL(minute/6) AS interval_no, SUM(order_count) AS total_orders GROUP BY 1 ORDER BY 1 OK - Complete Key Insight: The CEIL(minute / 6) formula maps any minute to its interval number. Minutes 1-6 map to 1, minutes 7-12 map to 2, etc. This avoids complex CASE statements and provides an elegant mathematical solution for interval grouping problems. TutorialsPoint - Calculate Orders Within Each Interval | Optimal Solution
Asked in
Amazon 12 Microsoft 8 Meta 6
28.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen