You are given two tables: Boxes and Chests. Each box may contain a chest, and both boxes and chests can contain apples and oranges.
Write a SQL query to count the total number of apples and oranges across all boxes. If a box contains a chest, you must include the fruits from both the box and its chest in the total count.
The result should return two columns:
apple_count- Total number of applesorange_count- Total number of oranges
Table Schema
| Column Name | Type | Description |
|---|---|---|
box_id
PK
|
int | Unique identifier for each box |
chest_id
|
int | Foreign key reference to Chests table (nullable) |
apple_count
|
int | Number of apples in the box |
orange_count
|
int | Number of oranges in the box |
| Column Name | Type | Description |
|---|---|---|
chest_id
PK
|
int | Unique identifier for each chest |
apple_count
|
int | Number of apples in the chest |
orange_count
|
int | Number of oranges in the chest |
Input & Output
| box_id | chest_id | apple_count | orange_count |
|---|---|---|---|
| 1 | 1 | 1 | 4 |
| 2 | 4 | 4 |
| chest_id | apple_count | orange_count |
|---|---|---|
| 1 | 3 | 1 |
| apple_count | orange_count |
|---|---|
| 8 | 9 |
Box 1 contains 1 apple + 4 oranges, plus chest 1 with 3 apples + 1 orange = 4 apples + 5 oranges from box 1. Box 2 contains 4 apples + 4 oranges with no chest. Total: 8 apples + 9 oranges.
| box_id | chest_id | apple_count | orange_count |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 1 |
| chest_id | apple_count | orange_count |
|---|---|---|
| 1 | 3 | 1 |
| 2 | 2 | 4 |
| apple_count | orange_count |
|---|---|
| 8 | 7 |
Box 1: (1+3) apples + (1+1) oranges = 4 apples + 2 oranges. Box 2: (2+2) apples + (1+4) oranges = 4 apples + 5 oranges. Total: 8 apples + 7 oranges.
| box_id | chest_id | apple_count | orange_count |
|---|---|---|---|
| 1 | 2 | 2 | |
| 2 | 3 | 3 |
| chest_id | apple_count | orange_count |
|---|
| apple_count | orange_count |
|---|---|
| 5 | 5 |
No boxes contain chests, so we only count fruits directly in boxes: 2+3 = 5 apples, 2+3 = 5 oranges.
Constraints
-
1 ≤ box_id ≤ 1000 -
0 ≤ apple_count, orange_count ≤ 1000 -
chest_idcan beNULLif box contains no chest -
Each
chest_idin Boxes table exists in Chests table (when not NULL)