Given a table containing key-value pairs, create an inverted table where the original keys become values and the original values become keys. When multiple keys have the same value, the inverted table should group those keys together.
Requirements:
- Transform keys to values and values to keys
- Handle duplicate values by grouping the corresponding keys
- All values are guaranteed to be strings
- Array indices should be treated as keys
Table Schema
| Column Name | Type | Description |
|---|---|---|
id
PK
|
int | Primary key identifier |
key_name
|
varchar | The original key or index |
value_content
|
varchar | The original value content |
Input & Output
| id | key_name | value_content |
|---|---|---|
| 1 | name | John |
| 2 | age | 25 |
| 3 | city | NYC |
| inverted_key | inverted_value |
|---|---|
| 25 | age |
| John | name |
| NYC | city |
Each key-value pair is inverted: the original values become the new keys, and the original keys become the new values. Since all values are unique, no aggregation is needed.
| id | key_name | value_content |
|---|---|---|
| 1 | a | hello |
| 2 | b | world |
| 3 | c | hello |
| inverted_key | inverted_value |
|---|---|
| hello | a,c |
| world | b |
When multiple keys have the same value ('hello'), the inverted result groups those keys together using comma separation. The value 'hello' maps to both 'a' and 'c', so the result shows 'a,c'.
| id | key_name | value_content |
|---|---|---|
| 1 | 0 | apple |
| 2 | 1 | banana |
| 3 | 2 | apple |
| inverted_key | inverted_value |
|---|---|
| apple | 0,2 |
| banana | 1 |
Array indices are treated as keys. The value 'apple' appears at indices 0 and 2, so it maps to '0,2' in the inverted result. The value 'banana' appears only at index 1.
Constraints
-
1 ≤ number of key-value pairs ≤ 1000 -
All values are guaranteed to be
strings -
Keys can be either
string namesorarray indices