题目
编写解决方案,使:
first_col
按照升序排列。second_col
按照 降序排列。
准备数据
python
Create table If Not Exists Data (first_col int, second_col int)
Truncate table Data
insert into Data (first_col, second_col) values ('4', '2')
insert into Data (first_col, second_col) values ('2', '3')
insert into Data (first_col, second_col) values ('3', '1')
insert into Data (first_col, second_col) values ('1', '4');
分析数据
a表
sqlselect row_number() over(order by first_col) as id, first_col from Data
b表
sqlselect row_number() over(order by second_col desc) as id, second_col from Data
根据关联条件将两表关联起来
sqlselect a.first_col, b.second_col from (select row_number() over(order by first_col) as id, first_col from Data) a join (select row_number() over(order by second_col desc) as id, second_col from Data) b on a.id = b.id;
总结
如果两个表关联条件字段相同,也可以使用using(关联的字段名)
比如这道题,最后可以使用"using(id) " 代替 " on a.id = b.id"
本题错误做法
sqlselect * from data order by first_col asc,second_col desc;
因为本题是单独让每列排序,而上面做法second_col的降序会在first_col升序的情况下再排序