• 数据(单行)处理函数和分组函数


    一,单行处理函数

       常用的数据处理函数如下表所示:

    单行处理函数
    lower转大写
    upper转小写
    substr取子串(substr{被截取的子串,起始下标(从1开始),被截长度})
    length取长度
    trim去空格
    str_to_date字符串(varchar)转日期(date)
    date_fromat日期格式化.。将date类型转换为一定格式的varchar类型。
    format设置千分位。使用:format(数字,'$999.999');
    round四舍五入。round(数字,保留到哪位)。0是保留到整数位,保留几位小数就写几,保留到几位整数就写负几。
    rand()生成0到1的随机数。要生成一百以内的随机数:select round(rand()*100,0) as in100 from user;
    ifnull

    将null转成一个具体值。如果不处理NULL,它与任何数据运算结果都是NULL。用法ifnull(数据,被当作哪个值)

           Notations:

    (1)concat(,)用于字符拼接。示例将首字母大写输出:

    select concat(upper(substr(userCode,1,1)),substr(userCode,2,length(userCode)-1)) from user;

    (2)如果写select 1000 as num from user; 会生成一个字段为num,字面值都是1000,行数跟user相同的列输出

      (3)case...when...then...when...then...else...end;使用例如给两种商品涨价:

     select productName,productCount as oldPrice,(case productDesc when '饮料-国酒' then productCount*1.2 when '食品-进口食用油' then productCount*1.3 else productCount end) as newPrice from bill;

    (4)if语句的使用:if(条件,1,0)表示满足条件则使用数据,不满足则不用

             单行处理函数(数据处理函数)的特点:一个输入对应一个输出,而多行处理函数就是多个输入对应一个输出。

    二,分组函数(多行处理函数):

            特点:输入多行,输出一行。

    多行处理函数
    count计数
    sum求和
    avg求平均
    max求最大值
    min求最小值

    Notations:

    (1)分组函数使用必须先进行分组。如果没有风,整张表默认为一份。(2)分组函数自动处理null。但如果使用如Count(*),是会计算null的,而Count(具体字段)不会计入null。(3)分组函数不能直接使用在where子句中,因为where执行顺序在分组函数之前,它执行的时候还没分组。(4)所有分组函数可以组合起来一起用

    三,分组查询

            一些需求需要分组:select...from...group by...order by...;

            执行顺序:1,from;2,where;3,group by;4,having;5,select;6,order by;

    //      先指定那张表查,再用where筛选有价值的数据,然后进行分组,分组后继续用having筛选,再用select把数据拿出来,最后进行排序

            分组举例:

    (1)select productDesc,sum(productCount) from bill group by productDesc;

    (2)   联合分组:select depto,job,max(sal) from emp group by depto,job;

    //       先按照depto分组,再按job分组,最后找出不同depto的不同job的max(sal)

    (3)使用having可以对被group by 分组后的数据进一步进行选择性过滤,having只能和group by 联用,不能替代where。如:

    select productDesc,max(productCount) from bill group by productDesc having max(productCount)>1000;

    Notations:上面的语句执行效率比较低,开发中优先选用where。可以先选择出大于1000的productCount,再按照productDesc分组,然后找到每个productDesc中productCount的最大值,如:

    select productDesc,max(productCount) from bill where productCount>1000 group by productDesc;

    如果有分组函数,那么select后面只能跟分组过后的字段,因为显示其他没分组的字段无意义或报错。

            

  • 相关阅读:
    Redis数据库【一文教必备操作】
    HCIE Routing&Switching之MPLS基础理论
    网络安全态势感知运营中心建设解决方案
    过程构成 中的小棱形 0..* 1..是什么意思过程构成 中的小棱形 0.. 1..*是什么意思
    卡奥斯第二届1024程序员节正式启动!
    【经验】Ubuntu18.04切换Python版本及环境,及VScode/pdb调试方法(全)
    常态化防疫下,社区该如何快速收集防疫信息?
    牛客_小白月赛_61
    golang大小端字节序
    [Mybatis-Plus笔记] MybatisPlus-01-入门案例与基本CRUD
  • 原文地址:https://blog.csdn.net/small_py_trade/article/details/124062073