按多列排序
我们可以向 .order_by() 方法传入多个参数,以按多列进行排序。实际上,还可以为每一列分别指定升序或降序。在 .order_by() 方法中,各列会从左到右依次完整排序。这意味着会先对第一列完全排序,然后在第一列每个相同值的分组内,再按照 .order_by() 中的下一列进行排序。这个过程会一直重复,直到 .order_by() 中的所有列都排序完成。
本练习是课程的一部分
Python 中的数据库入门
练习说明
- 从
census表中选择state和age两列的所有记录。 - 使用
.order_by()将state列按升序、age列按降序排序。(注意:desc已导入) - 在
connection上使用.execute()执行stmt,并用.fetchall()获取所有结果。 - 打印前 20 条结果。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Build a query to select state and age: stmt
stmt = select([____, ____])
# Append order by to ascend by state and descend by age
stmt = stmt.order_by(____, ____)
# Execute the statement and store all the records: results
results = ____
# Print the first 20 results
print(____)