You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: LeetCode SQL 50 Solution/1204. Last Person to Fit in the Bus.sql
+73Lines changed: 73 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -73,3 +73,76 @@ ORDER BY a.turn DESC
73
73
LIMIT1;
74
74
75
75
76
+
Let's break down the query step by step to understand what it does:
77
+
78
+
---
79
+
80
+
### 1. Self-Join of the Table
81
+
82
+
```sql
83
+
FROM
84
+
Queue AS a,
85
+
Queue AS b
86
+
WHERE a.turn >= b.turn
87
+
```
88
+
89
+
- **Self-Join:**
90
+
The query treats the `Queue` table as two separate aliases: `a` and `b`. This is a self-join, meaning each row in `a` is paired with rows in `b`.
91
+
92
+
- **Join Condition (`a.turn >= b.turn`):**
93
+
For each row in alias `a`, the query pairs it with every row in alias `b` that has a `turn` value less than or equal to `a.turn`.
94
+
- **Purpose:** This setup is used to accumulate data from the start of the queue up to the current person's turn.
95
+
96
+
---
97
+
98
+
### 2. Grouping by Person
99
+
100
+
```sql
101
+
GROUP BY a.person_id
102
+
```
103
+
104
+
-**Grouping:**
105
+
The query groups the resulting joined rows by `a.person_id`.
106
+
-**Effect:** For each person in the queue (represented by alias `a`), all rows (from`b`) where`b.turn` is less than or equal to `a.turn` are aggregated together.
107
+
108
+
---
109
+
110
+
### 3. Calculating the Cumulative Weight
111
+
112
+
```sql
113
+
HAVING SUM(b.weight) <= 1000
114
+
```
115
+
116
+
-**Cumulative Sum:**
117
+
Within each group, the query calculates the sum of `b.weight`.
118
+
-**Condition:** The `HAVING` clause filters out groups where the cumulative weight (i.e., the sum of weights from the start of the queue up to the current person's turn) exceeds 1000.
119
+
- **Interpretation:** Only those persons for whom the cumulative weight of all people before and including them is **less than or equal to 1000** are kept.
120
+
121
+
---
122
+
123
+
### 4. Selecting the Result
124
+
125
+
```sql
126
+
SELECT a.person_name
127
+
```
128
+
129
+
- **Result Column:**
130
+
After filtering, the query selects the `person_name` from alias `a` for each group that passed the `HAVING` condition.
131
+
132
+
---
133
+
134
+
### 5. Ordering and Limiting the Result
135
+
136
+
```sql
137
+
ORDER BY a.turn DESC
138
+
LIMIT 1;
139
+
```
140
+
141
+
- **Ordering:**
142
+
The results are ordered by `a.turn` in descending order.
143
+
- **Purpose:** This ensures that among all persons whose cumulative weight is ≤ 1000, the one with the **latest (highest) turn** is at the top.
144
+
145
+
- **Limiting:**
146
+
The `LIMIT 1` clause restricts the output to only the top result, effectively returning **one person**.
0 commit comments