MySQL排序_20160926

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL排序_20160926相关的知识,希望对你有一定的参考价值。

在工作中对数据进行排序也是最常用的,比如根据用户的下单金额降序 或者对销售业绩进行降序排序 在考核员工KPI时候也经常用到

一、order  by 函数

order by 函数默认根据后面字段升序,使用降序使用

order by 字段名 desc写法

计算各城市各产品3个月份分别的订单额,以9月金额降序

1 SELECT city,productID,productname,SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201607,pay_money,NULL)) AS 7月金额,
2 SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201608,pay_money,NULL)) AS 8月金额,
3 SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201609,pay_money,NULL)) AS 9月金额
4 FROM test_a03order
5 GROUP BY city,productID
6 ORDER BY SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201609,pay_money,NULL)) DESC

技术分享

2、order by field()函数 自定义排序

类似于excel中自定义排序一样 mysql也支持根据字段自定义排序

2.1SQL 让城市以city_A,city_C,city_B,city_D,city_E 这样的排序  

对比2.2SQL  2.1SQL field 函数里面没有把city_F放到自定义顺序里面 结果city_F默认置前 这个在以后with rollup函数会用到

1 SELECT city,productID,productname,SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201607,pay_money,NULL)) AS 7月金额,
2 SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201608,pay_money,NULL)) AS 8月金额,
3 SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201609,pay_money,NULL)) AS 9月金额
4 FROM test_a03order
5 GROUP BY city,productID
6 ORDER BY FIELD(city,"city_A","city_C","city_B","city_D","city_E")

技术分享

2.2 SQL  field 函数里面把city_F放到自定义顺序里面 city_F置于最后

1 SELECT city,productID,productname,SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201607,pay_money,NULL)) AS 7月金额,
2 SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201608,pay_money,NULL)) AS 8月金额,
3 SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201609,pay_money,NULL)) AS 9月金额
4 FROM test_a03order
5 GROUP BY city,productID
6 ORDER BY FIELD(city,"city_A","city_C","city_B","city_D","city_E","city_F")

 技术分享

 

以上是关于MySQL排序_20160926的主要内容,如果未能解决你的问题,请参考以下文章

88. Merge Sorted Array----Array----Easy----20160926

SQL必知必会 20160926--

@121. Best Time to Buy and Sell Stock----Array----Easy---20160926

初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段

初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段

部分代码片段