美文网首页
SQL 排序

SQL 排序

作者: wpf_register | 来源:发表于2019-09-29 09:37 被阅读0次

    原文链接

    order by 函数

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

    SELECT city,productID,productname,
    SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201607,pay_money,NULL)) AS 7月金额,
    SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201608,pay_money,NULL)) AS 8月金额,
    SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201609,pay_money,NULL)) AS 9月金额
    FROM test_a03order
    GROUP BY city,productID
    ORDER BY SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201609,pay_money,NULL)) DESC
    
    order by field()函数 自定义排序
    1. 让城市以city_A,city_C,city_B,city_D,city_E 这样的排序
      默认city_F 在最前排
    SELECT city,productID,productname,
    SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201607,pay_money,NULL)) AS 7月金额,
    SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201608,pay_money,NULL)) AS 8月金额,
    SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201609,pay_money,NULL)) AS 9月金额
    FROM test_a03order
    GROUP BY city,productID
    ORDER BY FIELD(city,"city_A","city_C","city_B","city_D","city_E")
    
    1. order by field 函数里面把city_F放到自定义顺序里面
    SELECT city,productID,productname,
    SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201607,pay_money,NULL)) AS 7月金额,
    SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201608,pay_money,NULL)) AS 8月金额,
    SUM(IF(DATE_FORMAT(order_date,"%Y%m")=201609,pay_money,NULL)) AS 9月金额
    FROM test_a03order
    GROUP BY city,productID
    ORDER BY FIELD(city,"city_A","city_C","city_B","city_D","city_E","city_F")
    

    相关文章

      网友评论

          本文标题:SQL 排序

          本文链接:https://www.haomeiwen.com/subject/fnqbuctx.html