标签:
在工作中对数据进行排序也是最常用的,比如根据用户的下单金额降序 或者对销售业绩进行降序排序 在考核员工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")
标签:
原文地址:http://www.cnblogs.com/Mr-Cxy/p/5910291.html