码迷,mamicode.com
首页 > 数据库 > 详细

MySQL排序_20160926

时间:2016-09-26 19:58:18      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

在工作中对数据进行排序也是最常用的,比如根据用户的下单金额降序 或者对销售业绩进行降序排序 在考核员工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

标签:

原文地址:http://www.cnblogs.com/Mr-Cxy/p/5910291.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!