[英]SQL sort and order table
I've been trying this but haven't achieved the exact result I want.我一直在尝试这个,但没有达到我想要的确切结果。
I have this table :我有这张桌子:
id aviacompany destination departure_time duration
1 Alaska Air ATL 09-45 180
2 Alaska Air ATL 00-56 195
3 Alaska Air LAS 01-00 304
4 JetBlue MIA 06-10 256
5 JetBlue ATL 09-50 200
6 JetBlue MIA 18-43 270
7 JetBlue SFO 23-24 180
8 Silver DTW 07-10 120
9 Silver SEA 18-01 137
10 Silver DTW 19-32 183
I want to sort by the total number of flights operated by each aviacompany in descending order;我想按每个航空公司运营的航班总数降序排序;
• In case of ties, sort by name of the aviacompany in alphabetical order • 如果出现平局,请按航空公司名称的字母顺序排序
• Then, sort by the total number of flights to a particular destination operated by the same aviacompany • 然后,按同一航空公司运营的飞往特定目的地的航班总数排序
• In case of ties, sort by the destination column in alphabetical order • 如果出现平局,请按目标列按字母顺序排序
• Finally, if there are still ties, sort by the departure_time column in chronological order. • 最后,如果仍有平局,按department_time 列按时间顺序排序。
Output should look like this: Output 应如下所示:
id destination departure_time
4 MIA 06-10
6 MIA 18-43
5 ATL 09-50
7 SFO 23-24
2 ATL 00-56
1 ATL 09-45
3 LAS 01-00
8 DTW 07-10
10 DTW 19-32
9 SEA 18-01
Thanks谢谢
You can use window functions to derive the required sort criteria, assuming you are using MySql 8您可以使用window 函数来导出所需的排序标准,假设您使用的是 MySql 8
select id, destination, departure_time
from (
select *,
Count(*) over(partition by aviacompany) aQty,
Count(*) over(partition by aviacompany,destination) dQty
from t
)t
order by
aQty desc,
aviacompany,
dQty desc,
destination,
departure_time
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.