You are given a table cities with information about cities in different states.
Write a SQL query to:
- Find all cities in each state and combine them into a comma-separated string
- Only include states that have at least 3 cities
- Only include states where at least one city starts with the same letter as the state name
- Return results ordered by the count of matching-letter cities in descending order, then by state name in ascending order
- Cities in each row should be ordered alphabetically
Example: For state "Texas" with cities ["Tyler", "Temple", "Taylor", "Dallas"], the matching cities are "Tyler", "Temple", "Taylor" (all start with 'T'), so matching_letter_count = 3.
Table Schema
| Column Name | Type | Description |
|---|---|---|
state
PK
|
varchar | State name |
city
PK
|
varchar | City name within the state |
Input & Output
| state | city |
|---|---|
| New York | New York City |
| New York | Newark |
| New York | Buffalo |
| New York | Rochester |
| California | San Francisco |
| California | Sacramento |
| California | San Diego |
| California | Los Angeles |
| Texas | Tyler |
| Texas | Temple |
| Texas | Taylor |
| Texas | Dallas |
| Pennsylvania | Philadelphia |
| Pennsylvania | Pittsburgh |
| Pennsylvania | Pottstown |
| state | cities | matching_letter_count |
|---|---|---|
| Pennsylvania | Philadelphia, Pittsburgh, Pottstown | 3 |
| Texas | Dallas, Taylor, Temple, Tyler | 3 |
| New York | Buffalo, Newark, New York City, Rochester | 2 |
Pennsylvania: 3 cities, all start with 'P' → matching_letter_count = 3
Texas: 4 cities, 3 start with 'T' (Taylor, Temple, Tyler) → matching_letter_count = 3
New York: 4 cities, 2 start with 'N' (Newark, New York City) → matching_letter_count = 2
California: Excluded because no cities start with 'C'
| state | city |
|---|---|
| Florida | Fort Lauderdale |
| Florida | Fresno |
| Florida | Miami |
| Nevada | Las Vegas |
| Nevada | Reno |
| state | cities | matching_letter_count |
|---|---|---|
| Florida | Fort Lauderdale, Fresno, Miami | 2 |
Florida: Has exactly 3 cities (meets minimum), 2 cities start with 'F' → included with matching_letter_count = 2
Nevada: Only has 2 cities (below minimum of 3) → excluded
Constraints
-
1 ≤ number of cities ≤ 1000 -
stateandcitycontain only letters and spaces -
Each
(state, city)combination is unique