Order Two Columns Independently Problem
#2159
Description
LeetCode Problem 2159.
Table: Data
+-------------+------+
| Column Name | Type |
+-------------+------+
| first_col | int |
| second_col | int |
+-------------+------+
This table may contain duplicate rows.
Write a solution to independently:
- order
first_colin ascending order. - order
second_colin descending order.
The result format is in the following example.
Example 1:
Input:
Data table:
+-----------+------------+
| first_col | second_col |
+-----------+------------+
| 4 | 2 |
| 2 | 3 |
| 3 | 1 |
| 1 | 4 |
+-----------+------------+
Output:
+-----------+------------+
| first_col | second_col |
+-----------+------------+
| 1 | 4 |
| 2 | 3 |
| 3 | 2 |
| 4 | 1 |
+-----------+------------+
Solution
Approach: Number each column separately
The two columns have to be sorted separately and then placed side by side, so number the values of each column in its own order and join the numbers. ROW_NUMBER() (not RANK) is the right numbering because duplicates are allowed and every row must get a distinct partner; with RANK, equal values would share a number and the join would multiply rows.
WITH a AS (
SELECT first_col,
ROW_NUMBER() OVER (ORDER BY first_col ASC) AS rn
FROM Data
),
b AS (
SELECT second_col,
ROW_NUMBER() OVER (ORDER BY second_col DESC) AS rn
FROM Data
)
SELECT a.first_col, b.second_col
FROM a
JOIN b ON a.rn = b.rn;