Order Two Columns Independently - Problem
Given a table Data with two integer columns first_col and second_col, write a SQL query to independently sort the columns:
- Sort
first_colin ascending order - Sort
second_colin descending order
The result should combine the sorted values by their row positions, not by their original relationships.
Table Schema
Data
| Column Name | Type | Description |
|---|---|---|
first_col
|
int | First integer column to be sorted ascending |
second_col
|
int | Second integer column to be sorted descending |
Note: This table may contain duplicate rows. No inherent relationship between column values.
Input & Output
Example 1 — Basic Independent Sorting
Input Table:
| first_col | second_col |
|---|---|
| 1 | 4 |
| 3 | 2 |
| 2 | 3 |
Output:
| first_col | second_col |
|---|---|
| 1 | 4 |
| 2 | 3 |
| 3 | 2 |
💡 Note:
The first_col is sorted in ascending order: [1, 2, 3]. The second_col is sorted in descending order: [4, 3, 2]. The results are combined by their new positions.
Example 2 — With Duplicate Values
Input Table:
| first_col | second_col |
|---|---|
| 2 | 1 |
| 1 | 1 |
| 2 | 2 |
| 1 | 2 |
Output:
| first_col | second_col |
|---|---|
| 1 | 2 |
| 1 | 2 |
| 2 | 1 |
| 2 | 1 |
💡 Note:
With duplicates, first_col ascending gives [1, 1, 2, 2] and second_col descending gives [2, 2, 1, 1]. The sorting maintains duplicate values while reordering independently.
Example 3 — Single Row
Input Table:
| first_col | second_col |
|---|---|
| 5 | 10 |
Output:
| first_col | second_col |
|---|---|
| 5 | 10 |
💡 Note:
With only one row, both columns remain unchanged as there's nothing to sort against.
Constraints
-
1 ≤ n ≤ 1000where n is the number of rows -
first_colandsecond_colcontain integers - The table may contain duplicate rows
Visualization
Tap to expand
Understanding the Visualization
1
Input Table
Original data with unsorted columns
2
Independent Sorting
Use ROW_NUMBER() with different ORDER BY
3
Position Join
Combine sorted columns by row position
Key Takeaway
🎯 Key Insight: Use window functions to sort columns independently while maintaining row alignment through position-based joining
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code