首页 > 代码库 > MySQL排序_20160926
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_a03order5 GROUP BY city,productID6 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_a03order5 GROUP BY city,productID6 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_a03order5 GROUP BY city,productID6 ORDER BY FIELD(city,"city_A","city_C","city_B","city_D","city_E","city_F")
MySQL排序_20160926
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。