Professional Documents
Culture Documents
1. **Declaration of Variables:**
```sql
```
This declares a variable `@numSeats` and sets it to the number of seats the user is requesting. In
this case, it is set to 5.
```sql
WITH SeatAvailability AS (
SELECT
seat_number,
ROW_NUMBER() OVER (PARTITION BY CASE WHEN status = 'A' THEN 0 ELSE 1 END ORDER BY
seat_number) AS grp
FROM
YourTable
```
This CTE, named `SeatAvailability`, is used to calculate groups of adjacent seats based on their
availability status. It uses the `ROW_NUMBER()` window function to assign sequential numbers to
the seats and then calculates the difference between the sequential numbers of all seats and those
of available seats ('A'). This difference is used to create groups of adjacent available seats.
- `ROW_NUMBER() OVER (PARTITION BY CASE WHEN status = 'A' THEN 0 ELSE 1 END ORDER BY
seat_number)`: Assigns a sequential number to each seat within partitions. The partition is based on
the availability status, with 'A' getting a partition number of 0 and 'B' getting a partition number of 1.
- `AS grp`: Calculates the difference between the two row numbers, creating groups of adjacent
seats.
3. **Main Query:**
```sql
SELECT
MIN(seat_number) AS start_seat,
MAX(seat_number) AS end_seat
FROM
SeatAvailability
WHERE
status = 'A'
GROUP BY
grp
HAVING
ORDER BY
start_seat;
```
The main query selects the minimum and maximum seat numbers for each group of adjacent
available seats (`grp`). It filters only those seats where the status is 'A' (available), groups them by the
`grp` value, and then filters the groups to include only those with a count of available seats greater
than or equal to the requested number of seats (`@numSeats`). Finally, it orders the result by the
start seat number.
- `HAVING COUNT(*) >= @numSeats`: Ensures that the group has at least `@numSeats` available
seats.