zoukankan      html  css  js  c++  java
  • Hive-03 查询

      Hive中执行SQL语句时,出现类似于“Display all 469 possibilities? (y or n)”的错误,
    根本原因是因为SQL语句中存在tab键导致,tab键在linux系统中是有特殊含义的。

    基本查询

    desc formatted stu_buck;
    desc stu_buck;

    创建部门表
    create table if not exists dept(
    deptno int,
    dname string,
    loc int)
    row format delimited fields terminated by '	';    
    创建员工表          
    hive (default)> create table if not exists emp(
                  > empno int, enane string, job string, mgr int, hiredate string, sal double, comm double, deptno int)
                  > row format delimited fields terminated by '	';
    导入数据
    hive (default)> load data local inpath '/opt/module/datas/emp.txt' into table emp;
    hive (default)> load data local inpath '/opt/module/datas/dept.txt' into table dept;
    hive (default)> select * from emp;
    hive (default)> select empno, ename from emp;
    hive (default)> select ename AS name, deptno dn from emp;
    hive (default)> select sal +1 from emp;
    常用函数
    count(*)  max(sal) min(sal) sum(sal) avg(sal) 
    LIMIT子句用于限制返回的行数。
    hive (default)> select * from emp limit 5;

    Where语句

    hive (default)> select * from emp where sal >1000;
    注意:where子句中不能使用字段别名。
    ① 比较运算符(Between/In/ Is Null)
    
    查询工资是1500或5000的员工信息
    hive (default)> select * from emp where sal IN (1500, 5000);
    
    ② Like和RLike
    1)使用LIKE运算选择类似的值
    2)选择条件可以包含字符或数字:
    % 代表零个或多个字符(任意个字符)。
    _ 代表一个字符。
    3)RLIKE子句是Hive中这个功能的一个扩展,其可以通过Java的正则表达式这个更强大的语言来指定匹配条件。
    查找以2开头薪水的员工信息
    hive (default)> select * from emp where sal LIKE '2%';
        (2)查找第二个数值为2的薪水的员工信息
    hive (default)> select * from emp where sal LIKE '_2%';
        (3)查找薪水中含有2的员工信息
    hive (default)> select * from emp where sal RLIKE '[2]';
    ③ 逻辑运算符(And/Or/Not

    not in
    not null尽量不使用它们,影响效率

    分组

    GROUP BY语句通常会和聚合函数一起使用,按照一个或者多个列队结果进行分组,然后对每个组执行聚合操作。

    1)where后面不能写分组函数,而having后面可以使用分组函数。

    2)having只用于group by分组统计语句。

    分组group by xx字段,select后边跟的字段必须跟group by字段有关聚合函数如count( * )或者这个字段;不能是别的字段!!!

    select t1.base,  t1.name,  count(*) from (select concat(constellation, ",", blood_type) base, name from person_info) t1 group by base; select后边不能要name;

    1)计算emp表每个部门的平均工资
    hive (default)> select t.deptno, avg(t.sal) avg_sal from emp t group by t.deptno;
    2)计算emp每个部门中每个岗位的最高薪水 hive (default)> select t.deptno, t.job, max(t.sal) max_sal from emp t group by t.deptno, t.job; 求每个部门的平均薪水大于2000的部门 hive (default)> select deptno, avg(sal) avg_sal from emp group by deptno having avg_sal > 2000;
    group by了,select后边的字段必须是group by的字段或者使用聚合函数,否则不能加其他字段;
    select substring(orderdate, 6, 2),count(*) from business group by substring(orderdate,6,2);
    执行顺序: from...where...select...group by...having...order by...
    
    select substring(orderdate, 6, 2) month, count(*) from business group by month;
    Error: Error while compiling statement: FAILED: SemanticException Line 0:-1 Invalid table alias or column reference 'year': 
    (possible column names are: name, orderdate, cost) (state=42000,code=40000)

    Join语句

    Hive支持通常的SQL JOIN语句,但是只支持等值连接,不支持非等值连接。
    表的别名好处: 1)使用别名可以简化查询。 2)使用表名前缀可以提高执行效率。
    
    ① 内连接
    0: jdbc:hive2://hadoop101:10000> select e.empno, e.emane, d.deptno, d.dname from emp e join dept d on e.deptno=d.deptno;
    ② 左外连接
    0: jdbc:hive2://hadoop101:10000> select e.empno, e.emane, d.deptno, d.dname from emp e left join dept d on e.deptno=d.deptno;
    ③ 右外连接:JOIN操作符右边表中符合WHERE子句的所有记录将会被返回。
    
    hive (default)> select e.empno, e.ename, d.deptno from emp e right join dept d on e.deptno = d.deptno;
    
    ④ 满外连接:将会返回所有表中符合WHERE语句条件的所有记录。如果任一表的指定字段没有符合条件的值的话,那么就使用NULL值替代。
    
    hive (default)> select e.empno, e.ename, d.deptno from emp e full join dept d on e.deptno = d.deptno;
    
    ⑤ 多表连接
    hive (default)> create table if not exists location(
                  > loc int, loc_name string)
                  > row format delimited fields terminated by '	';
    OK
    Time taken: 0.3 seconds
    hive (default)> load data local inpath '/opt/module/datas/location.txt' into table location;
      多表连接查询
    0: jdbc:hive2://hadoop101:10000> select e.empno, e.emane, d.dname, l.loc_name from emp e join dept d on e.deptno=d.deptno join location l on d.loc=l.loc; //number of mappers: 1; number of reducers: 0
    优化:当对3个或者更多表进行join连接时,如果每个on子句都使用相同的连接键的话,那么只会产生一个MapReduce job。
    
    ⑥ 笛卡尔积
    hive (default)> select empno, dname from emp, dept;
    
    ⑦ 连接谓词中不支持or

    排序| 全局、reduce内部、分区

    ① 全局排序order by, 只有一个Reduce,全局查找; 默认升序, desc是降序;
    0: jdbc:hive2://hadoop101:10000> select * from emp order by sal;    //默认升序
    0: jdbc:hive2://hadoop101:10000> select * from emp order by sal desc;  //降序
    
    ② 按别名排序 | 多个列排序之间用,
    0: jdbc:hive2://hadoop101:10000> select ename,deptno, sal*2 twosalary from emp order by deptno, twosalary; //order by 字段;select 字段,必须写上排序的字段,否则出错!!
    0: jdbc:hive2://hadoop101:10000> select deptno, emane, sal from emp order by deptno, sal;  // deptno相同了再按sal排序; mappers: 1; number of reducers: 1
    
    ③ 每个MapReduce内部排序sort by;对于大规模的数据集order by的效率非常低;Sort by为每个reducer产生一个排序文件。每个Reducer内部进行排序,对全局结果集来说不是排序。
     set mapreduce.job.reduces=3;
     set mapreduce.job.reduces;
     select * from emp sort by deptno desc;
    根据部门编号降序查看员工信息
    hive (default)> select * from emp sort by deptno desc;  //下面语句是将查询结果集导入本地文件
    0: jdbc:hive2://hadoop101:10000> insert overwrite local directory '/opt/module/datas/sortby-result' select * from emp sort by deptno desc; 
      // number of mappers: 1; number of reducers: 3 ④ 分区排序 distribute by; 控制某个特定行应该到哪个reducer; distribute by的分区规则是: 根据分区字段的hash码与reduce的个数进行模除后,余数相同的分到一个区。 Hive要求DISTRIBUTE BY语句要写在SORT BY语句之前 0: jdbc:hive2://hadoop101:10000> insert overwrite local directory '/opt/module/datas/sortby-result' select * from emp sort by deptno desc; 0: jdbc:hive2://hadoop101:10000> insert overwrite local directory '/opt/module/datas/distribute-result' select * from emp distribute by deptno sort by empno desc; ⑤ cluster by 当distribute by和sorts by字段相同时,可以使用cluster by方式。 除了具有distribute by的功能(分区)外还兼具sort by即reduce内部排序的功能。但是排序只能是升序排序,不能指定排序规则为ASC或者DESC。 0: jdbc:hive2://hadoop101:10000> select * from emp cluster by deptno; 0: jdbc:hive2://hadoop101:10000> select * from emp distribute by deptno sort by deptno;

     分桶及抽样查询

    分区提供一个隔离数据和优化查询的便利方式。不过,并非所有的数据集都可形成合理的分区。对于一张表或者分区,Hive 可以进一步组织成桶,也就是更为细粒度的数据范围划分。

    分桶是将数据集分解成更容易管理的若干部分的另一个技术。

    分区针对的是数据的存储路径;分桶针对的是数据文件。

    创建数据
    create table stu_buck(id int, name string)
    clustered by(id) into 4 buckets
    row format delimited fields terminated by '	';
    查看表结构
    hive (default)> desc formatted stu_buck;
    Num Buckets:            4  
    导入数据到分桶表中
    hive (default)> load data local inpath '/opt/module/datas/student.txt' into table
     stu_buck;
    查看创建的分桶表中是并没有分成4个桶;没有经过mapreduce
    方式二:
    创建分桶表时,数据通过子查询的方式导入
    (1)先建一个普通的stu表
    create table stu(id int, name string)
    row format delimited fields terminated by '	';
    (2)向普通的stu表中导入数据
    load data local inpath '/opt/module/datas/student.txt' into table stu;
    (3)清空stu_buck表中数据
    truncate table stu_buck;
    select * from stu_buck;
    (4)导入数据到分桶表,通过子查询的方式
    insert into table stu_buck select id, name from stu;
    
    发现还是只有一个分桶; 因为数据量太小了;
    
    (5)需要设置一个属性;再来一遍!
    hive (default)> set hive.enforce.bucketing=true;
    hive (default)> set mapreduce.job.reduces=-1;
    hive (default)> truncate table stu_buck;
    hive (default)> insert into table stu_buck select id, name from stu;
    0: jdbc:hive2://hadoop101:10000> select * from stu_buck;  //从结果中看到分成了4个桶; 
    +--------------+----------------+--+
    | stu_buck.id  | stu_buck.name  |
    +--------------+----------------+--+
    | 1016         | ss16           |
    | 1012         | ss12           |
    | 1008         | ss8            |
    | 1004         | ss4            |
    | 1009         | ss9            |
    | 1005         | ss5            |
    | 1001         | ss1            |
    | 1013         | ss13           |
    | 1010         | ss10           |
    | 1002         | ss2            |
    | 1006         | ss6            |
    | 1014         | ss14           |
    | 1003         | ss3            |
    | 1011         | ss11           |
    | 1007         | ss7            |
    | 1015         | ss15           |
    +--------------+----------------+--+
    16 rows selected (0.09 seconds)
    
    分桶规则:
    根据结果可知:Hive的分桶采用对分桶字段的值进行哈希,然后除以桶的个数求余的方式决定该条记录存放在哪个桶当中

    抽样查询

    对于非常大的数据集,有时用户需要使用的是一个具有代表性的查询结果而不是全部结果。Hive可以通过对表进行抽样来满足这个需求。

    y必须是table总bucket数的倍数或者因子。hive根据y的大小,决定抽样的比例。例如,table总共分了4份,当y=2时,抽取(4/2=)2个bucket的数据,当y=8时,抽取(4/8=)1/2个bucket的数据。

    x表示从哪个bucket开始抽取,如果需要取多个分区,以后的分区号为当前分区号加上y。例如,table总bucket数为4,tablesample(bucket 1 out of 2),表示总共抽取(4/2=)2个bucket的数据,抽取第1(x)个和第3(x+y)个bucket的数据。

    注意:x的值必须小于等于y的值,否则

    tablesample是抽样语句,语法:TABLESAMPLE(BUCKET x OUT OF y) 。
    
    0: jdbc:hive2://hadoop101:10000> select * from stu_buck tablesample(bucket 2 out of 2 on id);
    +--------------+----------------+--+
    | stu_buck.id  | stu_buck.name  |
    +--------------+----------------+--+
    | 1009         | ss9            |
    | 1005         | ss5            |
    | 1001         | ss1            |
    | 1013         | ss13           |
    | 1003         | ss3            |
    | 1011         | ss11           |
    | 1007         | ss7            |
    | 1015         | ss15           |
    
    tablesample(bucket 2 out of 2 on id) //总共抽取4/2=2个bucket的数据,从第2个开始---第2+2个bucket;总共2个
    
    0: jdbc:hive2://hadoop101:10000> select * from stu_buck tablesample(bucket 3 out of 8 on id); //总共抽取4/8=0.5个bucket的数据,从第3个开始;
    +--------------+----------------+--+
    | stu_buck.id | stu_buck.name |
    +--------------+----------------+--+
    | 1010 | ss10 |
    | 1002 | ss2 |
    +--------------+----------------+--+
    2 rows selected (0.148 seconds)

    常用查询函数

    空字段赋值

    NVL:给值为NULL的数据赋值,它的格式是NVL( value,default_value)。它的功能是如果value为NULL,则NVL函数返回default_value的值,否则返回value的值,如果两个参数都为NULL ,则返回NULL。

    0: jdbc:hive2://hadoop101:10000> select comm, nvl(comm, -1) from emp;
    +---------+---------+--+
    |  comm   |   _c1   |
    +---------+---------+--+
    | NULL    | -1.0    |
    | 300.0   | 300.0   |
    | 500.0   | 500.0   |
    | NULL    | -1.0    |
    | 1400.0  | 1400.0  |
    | NULL    | -1.0    |
    | NULL    | -1.0    |
    | NULL    | -1.0    |
    | NULL    | -1.0    |
    | 0.0     | 0.0     |
    | NULL    | -1.0    |
    | NULL    | -1.0    |
    | NULL    | -1.0    |
    | NULL    | -1.0    |
    +---------+---------+--+
    14 rows selected (0.125 seconds)
    
    0: jdbc:hive2://hadoop101:10000> select comm, nvl(comm, mgr) from emp;  如果员工的comm为NULL,则用领导id代替

    CASE WHEN

    建表load数据

    hive (default)> create table emp_sex(
                  > name string, dept_id string, sex string)
                  > row format delimited fields terminated by '	';
    OK
    Time taken: 1.169 seconds
    hive (default)> load data local inpath '/opt/module/datas/emp_sex.txt' into table emp_sex;
    Loading data to table default.emp_sex
    Table default.emp_sex stats: [numFiles=1, totalSize=78]
    OK
    Time taken: 0.516 seconds
    View Code
    select * from emp_sex;
    emp_sex.name    emp_sex.dept_id    emp_sex.sex
    悟空    A    男
    八戒    A    男
    kris   B    男
    凤姐    A    女
    婷姐    B    女
    婷婷    B    女
    
    
    select 
        dept_id, 
        sum(case sex when '' then 1 else 0 end) male_count,
        sum(case sex when '' then 1 else 0 end) female_count 
    from emp_sex group by dept_id;
    +----------+-------------+---------------+--+
    | dept_id  | male_count  | female_count  |
    +----------+-------------+---------------+--+
    | A        | 2           | 1             |
    | B        | 1           | 2             |
    +----------+-------------+---------------+--+
    
    -------------case when的利用-------------- select name,sex, case when dept_id = 'A' then '1班 '
    when dept_id = 'B' then '2班 '
    when dept_id = 'C' then '3班'
    else dept_id end as dept_id from emp_sex; 悟空 男 1班 八戒 男 1班 kris 男 2班 凤姐 女 1班 婷姐 女 2班 婷婷 女 2班

      使用case when行转列

    select * from score; //数据如下:
    score.name    score.subject    score.score
    孙悟空    语文    87
    孙悟空    数学    95
    孙悟空    英语    68
    大海    语文    94
    大海    数学    56
    大海    英语    84
    kris    语文    64
    kris    数学    86
    kris    英语    84
    婷婷    语文    65
    婷婷    数学    85
    婷婷    英语    78
    View Code
    如果这样子写会出现如下这样子的数据情况:
    select
        name,
        case when subject='语文' then s.score else 0 end Chinese,
        case when subject='数学' then s.score else 0 end Math,
        case when subject='英语' then s.score else 0 end English
    from score s;
    name    chinese    math    english
    孙悟空    87    0    0
    孙悟空    0    95    0
    孙悟空    0    0    68
    大海     94    0    0
    大海     0    56    0
    大海     0    0    84
    kris    64    0    0
    kris    0    86    0
    kris    0    0    84
    婷婷    65    0    0
    婷婷    0    85    0
    婷婷    0    0    78
    View Code
    方法一:使用case when 行转列
    select
        name,
        max(case when subject='语文' then s.score else 0 end) Chinese,
        max(case when subject='数学' then s.score else 0 end) Math,
        max(case when subject='英语' then s.score else 0 end) English
    from score s group by name;
    
    方法二: 使用union(可以去重,删除重复行) 或者union all, Hive1.2.0之前的版本仅支持union all, 使用union时第一个select要把别名写全,其他的select可补0
    max或者sum函数都可以;
    select name, max(chinese_score) chinese_score,max(math_score) chinese_score,max(english_score) chinese_score from( select name,subject, score chinese_score,0 math_score ,0 english_score from score where subject = '语文' union select name,subject,0, score math_score,0 from score where subject = '数学' union select name,subject,0,0,score english_score from score where subject = '英语' ) t group by name

    ===>最后执行结果如下:

    name    chinese    math    english
    kris        64    86    84
    大海         94    56    84
    婷婷         65    85    78
    孙悟空        87    95     68

    行转列

    COLLECT_SET(col):函数只接受基本数据类型,它的主要作用是将某字段的值进行去重汇总,产生array类型字段

    CONCAT_WS(separator, str1, str2,...):它是一个特殊形式的 CONCAT()。第一个参数剩余参数间的分隔符。分隔符可以是与剩余参数一样的字符串。如果分隔符是 NULL,返回值也将为 NULL。这个函数会跳过分隔符参数后的任何 NULL 和空字符串。分隔符将被加到被连接的字符串之间;

    CONCAT(string A/col, string B/col…):返回输入字符串连接后的结果,支持任意个输入字符串; 如concat( constellation,  ",",  blood_type ) 将这两个字段以,分割合并一个字段;

     建表,导数据;

    [kris@hadoop101 datas]$ cat constellation.txt 
    大海    射手座  A
    kris    白羊座  B
    猪八戒  白羊座  A
    凤凤    射手座  A
    hive (default)> create table person_info(
                  > name string, constellation string, blood_type string)
                  > row format delimited fields terminated by '	';
    hive (default)> load data local inpath '/opt/module/datas/constellation.txt' into table person_info;
    View Code
    行转列:把多行转成1行 /
    select * from person_info; +-------------------+----------------------------+-------------------------+--+ | person_info.name | person_info.constellation | person_info.blood_type | +-------------------+----------------------------+-------------------------+--+ | 大海         | 射手座                | A | | kris         | 白羊座                 | B | | 猪八戒        | 白羊座                 | A | | 凤凤         | 射手座                 | A | +-------------------+----------------------------+-------------------------+--+ count(*)聚合函数,把多的聚合成一个; select
    t.base, count(*)
    from (select concat(constellation, ",", blood_type) base, name from person_info) t group by t.base; ---->>collect_set(col)同样也是聚合,产生array类型,把count换成collect_set即可;
    select
    t.base, collect_set(t.name)
    from (select concat(constellation, ",", blood_type) base, name from person_info) t group by t.base; +--------+--------------+--+ | base   | _c1 | +--------+--------------+--+ | 射手座,A | ["大海","凤凤"] | | 白羊座,A | ["猪八戒"] | | 白羊座,B | ["kris"] | +--------+--------------+--+ 使用oncat_ws("分隔符", 分割的东西)改下格式即可 select
    t.base, concat_ws("|", collect_set(t.name))
    from (select concat(constellation, ",", blood_type) base, name from person_info) t group by t.base; +--------+--------+--+ | base   | _c1 | +--------+--------+--+ | 射手座,A | 大海|凤凤 | | 白羊座,A | 猪八戒 | | 白羊座,B | kris | +--------+--------+--+

    列转行

    函数说明

    EXPLODE(col):将hive一列中复杂的array或者map结构拆分成多行。

    LATERAL VIEW

    用法:LATERAL VIEW udtf(expression) tableAlias AS columnAlias

    解释:用于和split, explode等UDTF一起使用,它能够将一列数据拆成多行数据,在此基础上可以对拆分后的数据进行聚合。

    建表(category类型为array)导入数据: category  array<string>  

    hive (default)> create table movie_info(
                  > movie string, category array<string>)
                  > row format delimited fields terminated by '	'
                  > collection items terminated by ',';
    OK
    Time taken: 0.101 seconds
    
    hive (default)> load data local inpath '/opt/module/datas/movie.txt' into table movie_info;
    《疑犯追踪》    悬疑,动作,科幻,剧情
    《Lie to me》    悬疑,警匪,动作,心理,剧情
    《战狼2》        战争,动作,灾难
    View Code
    列转行:把1行中的数据转为多行
    EXPLODE(col):将hive一列中复杂的array或者map结构拆分成多行。
    LATERAL VIEW
    用法:LATERAL VIEW udtf(expression) tableAlias AS columnAlias
    解释:用于和split, explode等UDTF一起使用,它能够将一列数据拆成多行数据,在此基础上可以对拆分后的数据进行聚合。

     select * from movie_info;
    +-------------------+-----------------------------+--+
    | movie_info.movie | movie_info.category |
    +-------------------+-----------------------------+--+
    | 《疑犯追踪》 | ["悬疑","动作","科幻","剧情"] |
    | 《Lie to me》 | ["悬疑","警匪","动作","心理","剧情"] |
    | 《战狼2》 | ["战争","动作","灾难"] |
    +-------------------+-----------------------------+--+


    select
    movie, category_name
    from movie_info
    lateral view explode(category) table_tmp as category_name;
    +--------------+----------------+--+ | movie | category_name | +--------------+----------------+--+ | 《疑犯追踪》 | 悬疑 | | 《疑犯追踪》 | 动作 | | 《疑犯追踪》 | 科幻 | | 《疑犯追踪》 | 剧情 | | 《Lie to me》 | 悬疑 | | 《Lie to me》 | 警匪 | | 《Lie to me》 | 动作 | | 《Lie to me》 | 心理 | | 《Lie to me》 | 剧情 | | 《战狼2》 | 战争 | | 《战狼2》 | 动作 | | 《战狼2》 | 灾难 | +--------------+----------------+--+ 12 rows selected (0.069 seconds) 分类,悬疑的有哪些电影?... 思路:先列转行,再行转列 [kris@hadoop101 datas]$ vi movie.txt 《疑犯追踪》 悬疑,动作,科幻,剧情 《Lie to me》 悬疑,警匪,动作,心理,剧情 《战狼2》 战争,动作,灾难 select
    t.category_name, concat_ws('|', COLLECT_SET(t.movie)) from (select movie, category_name from movie_info lateral view explode(category) table_tmp as category_name ) t group by t.category_name;
    +------------------+---------------------------+--+ | t.category_name | _c1 | +------------------+---------------------------+--+ | 剧情 | 《疑犯追踪》|《Lie to me》 | | 动作 | 《疑犯追踪》|《Lie to me》|《战狼2》 | | 心理 | 《Lie to me》 | | 战争 | 《战狼2》 | | 科幻 | 《疑犯追踪》 | | 悬疑 | 《疑犯追踪》|《Lie to me》 | | 灾难 | 《战狼2》 | | 警匪 | 《Lie to me》 | +------------------+---------------------------+--+

     

    创建表并load数据

    drop table tmp_test1;
    create table tmp_test1(
    col1 string,
    col2 string,
    col3 string
    )
    row format delimited fields terminated by '	'
    stored as textfile;
    
    load data local inpath '/opt/module/datas/1.txt' into table tmp_test1;
    
    a    b    1,2,3
    c    d    4,5,6
    View Code
    select * from tmp_test1;
    a    b    1,2,3
    c    d    4,5,6
    
    select col1,col2,col4 from tmp_test1 lateral view explode(split(col3, ',')) b as col4;
    col1    col2    col4
    a    b    1
    a    b    2
    a    b    3
    c    d    4
    c    d    5
    c    d    6

     

     

    窗口函数(开窗函数)

    相关函数说明

    OVER():指定分析函数工作的数据窗口大小,这个数据窗口大小可能会随着行的变而变化。

    CURRENT ROW:当前行

    n PRECEDING:往前n行数据

    n FOLLOWING:往后n行数据

    UNBOUNDED:起点,UNBOUNDED PRECEDING 表示从前面的起点, UNBOUNDED FOLLOWING表示到后面的终点

    LAG(col,n,default_val):往前第n行数据

    LEAD(col,n, default_val):往后第n行数据

    NTILE(n):把有序分区中的行分发到指定数据的组中,各个组有编号,编号从1开始,对于每一行,NTILE返回此行所属的组的编号。注意:n必须为int类型。

        substring( orderdate,6, 2)是从第6个字符开始分2个字符给我;

    
    

    (1)查询在2017年4月份购买过的顾客及总人数

     select * from business where substring(orderdate, 1, 7) = '2017-04';
    +----------------+---------------------+----------------+--+
    | business.name  | business.orderdate  | business.cost  |
    +----------------+---------------------+----------------+--+
    | jack           | 2017-04-06          | 42             |
    | mart           | 2017-04-08          | 62             |
    | mart           | 2017-04-09          | 68             |
    | mart           | 2017-04-11          | 75             |
    | mart           | 2017-04-13          | 94             |
    +----------------+---------------------+----------------+--+
    
     select name, count(*) from business where substring(orderdate, 1, 7) = '2017-04' group by name;
    +-------+------+--+
    | name  | _c1  |
    +-------+------+--+
    | jack  | 1    |
    | mart  | 4    |
    +-------+------+--+
    
    OVER():指定分析函数工作的数据窗口大小,这个数据窗口大小可能会随着行的变而变化; 
     select name, count(*) over () from business where substring(orderdate, 1, 7) = '2017-04' group by name;
    +-------+-----------------+--+
    | name  | count_window_0  |
    +-------+-----------------+--+
    | mart  | 2               | //count(*) over() ... group by name ..统计每个组数即有几个人
    | jack  | 2               |
    +-------+-----------------+--+

    (2)查询顾客的购买明细及月购买总额

     select *, sum(cost) over(partition by month(orderdate)) from business;  //sum(cost) over ()所有行相加;单独使用sum(cost)不行, Expression not in GROUP BY key name  
    +----------------+---------------------+----------------+---------------+--+
    | business.name  | business.orderdate  | business.cost  | sum_window_0  |
    +----------------+---------------------+----------------+---------------+--+
    | jack           | 2017-01-01          | 10             | 205           |
    | jack           | 2017-01-08          | 55             | 205           |
    | tony           | 2017-01-07          | 50             | 205           |
    | jack           | 2017-01-05          | 46             | 205           |
    | tony           | 2017-01-04          | 29             | 205           |
    | tony           | 2017-01-02          | 15             | 205           |
    | jack           | 2017-02-03          | 23             | 23            |
    | mart           | 2017-04-13          | 94             | 341           |
    | jack           | 2017-04-06          | 42             | 341           |
    | mart           | 2017-04-11          | 75             | 341           |
    | mart           | 2017-04-09          | 68             | 341           |
    | mart           | 2017-04-08          | 62             | 341           |
    | neil           | 2017-05-10          | 12             | 12            |
    | neil           | 2017-06-12          | 80             | 80            |
    +----------------+---------------------+----------------+---------------+--
    select name,orderdate,cost, sum(cost) over() as sample1,--所有行相加 sum(cost) over(partition by name) as sample2,--按name分组,组内数据相加 sum(cost) over(partition by name order by orderdate) as sample3,--按name分组,组内数据累加
    如果不加ORDER BY, 就没有窗口,计算范围是整个分区;
    加上ORDER BY, 默认窗口是RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW,就是排序后从分区第一行一直到当前行为止。
    sum(cost) over(partition by name order by orderdate rows between UNBOUNDED PRECEDING and current row ) as sample4 ,--和sample3一样,由起点到当前行的聚合 sum(cost) over(partition by name order by orderdate rows between 1 PRECEDING and current row) as sample5, --当前行和前面一行做聚合 sum(cost) over(partition by name order by orderdate rows between 1 PRECEDING AND 1 FOLLOWING ) as sample6,--当前行和前边一行及后面一行 sum(cost) over(partition by name order by orderdate rows between current row and UNBOUNDED FOLLOWING ) as sample7 --当前行及后面所有行 from business; rows必须跟在Order by 子句之后,对排序的结果进行限制,使用固定的行数来限制分区中的数据行数量

      3)查看顾客上次的购买时间

    LAG(col,n,default_val):往前第n行数据
     select *, lag(orderdate, 1, '1900-1-1') over(partition by name order by orderdate) as time1, lag(orderdate, 2) over (partition by name order by orderdate) as time2 from business;
    +----------------+---------------------+----------------+-------------+-------------+--+
    | business.name  | business.orderdate  | business.cost  |    time1    |    time2    |
    +----------------+---------------------+----------------+-------------+-------------+--+
    | jack           | 2017-01-01          | 10             | 1900-1-1    | NULL        |
    | jack           | 2017-01-05          | 46             | 2017-01-01  | NULL        |
    | jack           | 2017-01-08          | 55             | 2017-01-05  | 2017-01-01  |
    | jack           | 2017-02-03          | 23             | 2017-01-08  | 2017-01-05  |
    | jack           | 2017-04-06          | 42             | 2017-02-03  | 2017-01-08  |
    | mart           | 2017-04-08          | 62             | 1900-1-1    | NULL        |
    | mart           | 2017-04-09          | 68             | 2017-04-08  | NULL        |
    | mart           | 2017-04-11          | 75             | 2017-04-09  | 2017-04-08  |
    | mart           | 2017-04-13          | 94             | 2017-04-11  | 2017-04-09  |
    | neil           | 2017-05-10          | 12             | 1900-1-1    | NULL        |
    | neil           | 2017-06-12          | 80             | 2017-05-10  | NULL        |
    | tony           | 2017-01-02          | 15             | 1900-1-1    | NULL        |
    | tony           | 2017-01-04          | 29             | 2017-01-02  | NULL        |
    | tony           | 2017-01-07          | 50             | 2017-01-04  | 2017-01-02  |
    +----------------+---------------------+----------------+-------------+-------------+--+
    
    NTILE(n):把有序分区中的行分发到指定数据的组中,各个组有编号,编号从1开始,对于每一行,NTILE返回此行所属的组的编号。
    注意:n必须为int类型。

     4)查询前20%时间的订单信息

     select *, ntile(5) over(order by orderdate) sorted from business; //按orderdate排序, 分5组;前边都素每4行为1组;...
    +----------------+---------------------+----------------+---------+--+
    | business.name  | business.orderdate  | business.cost  | sorted  |
    +----------------+---------------------+----------------+---------+--+
    | jack           | 2017-01-01          | 10             | 1       |
    | tony           | 2017-01-02          | 15             | 1       |
    | tony           | 2017-01-04          | 29             | 1       |
    | jack           | 2017-01-05          | 46             | 2       |
    | tony           | 2017-01-07          | 50             | 2       |
    | jack           | 2017-01-08          | 55             | 2       |
    | jack           | 2017-02-03          | 23             | 3       |
    | jack           | 2017-04-06          | 42             | 3       |
    | mart           | 2017-04-08          | 62             | 3       |
    | mart           | 2017-04-09          | 68             | 4       |
    | mart           | 2017-04-11          | 75             | 4       |
    | mart           | 2017-04-13          | 94             | 4       |
    | neil           | 2017-05-10          | 12             | 5       |
    | neil           | 2017-06-12          | 80             | 5       |
    +----------------+---------------------+----------------+---------+--+
    14 rows selected (16.006 seconds)
    
     select *, ntile(5) over(order by orderdate) sorted from business) t where sorted=1;

    Rank

    RANK() 排序相同时会重复,总数不会变
    DENSE_RANK() 排序相同时会重复,总数会减少
    ROW_NUMBER() 会根据顺序计算

    0: jdbc:hive2://hadoop101:10000> select name, subject, score, rank() over(partition by subject order by score desc) rank_, dense_rank() over(partition by subject order by score desc) dense_rank_, row_number() over(partition by subject order by score desc) row_number_ from score; +-------+----------+--------+--------+--------------+--------------+--+ | name | subject | score | rank_ | dense_rank_ | row_number_ | +-------+----------+--------+--------+--------------+--------------+--+ | 孙悟空 | 数学 | 95 | 1 | 1 | 1 | | 宋宋 | 数学 | 86 | 2 | 2 | 2 | | 婷婷 | 数学 | 85 | 3 | 3 | 3 | | 大海 | 数学 | 56 | 4 | 4 | 4 | | 宋宋 | 英语 | 84 | 1 | 1 | 1 | | 大海 | 英语 |
    | | 婷婷 | 英语 | 78 | 3 | 2 | 3 | | 孙悟空 | 英语 | 68 | 4 | 3 | 4 | | 大海 | 语文 | 94 | 1 | 1 | 1 | | 孙悟空 | 语文 | 87 | 2 | 2 | 2 | | 婷婷 | 语文 | 65 | 3 | 3 | 3 | | 宋宋 | 语文 | 64 | 4 | 4 | 4 | +-------+----------+--------+--------+--------------+--------------+--+ 12 rows selected (17.168 seconds)

    系统内置函数

    1. 查看系统自带的函数

    hive> show functions;

    2.显示自带的函数的用法

    hive> desc function upper;

    3. 详细显示自带的函数的用法

    0: jdbc:hive2://hadoop101:10000> desc function extended datediff;

    +----------------------------------------------------------------------------------------------------------------------------------------------------------------------+--+
    |                                                                               tab_name                                                                               |
    +----------------------------------------------------------------------------------------------------------------------------------------------------------------------+--+
    | datediff(date1, date2) - Returns the number of days between date1 and date2                                                                                          |
    | date1 and date2 are strings in the format 'yyyy-MM-dd HH:mm:ss' or 'yyyy-MM-dd'. The time parts are ignored.If date1 is earlier than date2, the result is negative.  |
    | Example:                                                                                                                                                             |
    |    > SELECT datediff('2009-07-30', '2009-07-31') FROM src LIMIT 1;                                                                                                   |
    |   1                                                                                                                                                                  |
    +----------------------------------------------------------------------------------------------------------------------------------------------------------------------+--+
    View Code

    0: jdbc:hive2://hadoop101:10000> desc function extended regexp_replace;

    +----------------------------------------------------------------------------------------------+--+
    |                                           tab_name                                           |
    +----------------------------------------------------------------------------------------------+--+
    | regexp_replace(str, regexp, rep) - replace all substrings of str that match regexp with rep  |
    | Example:                                                                                     |
    |   > SELECT regexp_replace('100-200', '(d+)', 'num') FROM src LIMIT 1;                       |
    |   'num-num'                                                                                  |
    +----------------------------------------------------------------------------------------------+--+
    View Code

    日期处理函数

    1)date_format函数(根据格式整理日期)

    hive (gmall)> select date_format('2019-02-10','yyyy-MM');

    2019-02

    2)date_add函数(加减日期)

    hive (gmall)> select date_add('2019-02-10',-1);

    2019-02-09

    hive (gmall)> select date_add('2019-02-10',1);

    2019-02-11

    3)next_day函数

           1)取当前天的下一个周一

    hive (gmall)> select next_day('2019-02-12','MO')

    2019-02-18

      2)取当前周的周一

    hive (gmall)> select date_add(next_day('2019-02-12','MO'),-7);

    2019-02-11

    4)last_day函数(求当月最后一天日期)

    hive (gmall)> select last_day('2019-02-10');

    2019-02-28

    自定义UDF函数

    当Hive提供的内置函数无法满足你的业务处理需要时,此时就可以考虑使用用户自定义函数(UDF:user-defined function)。

    UDF(User-Defined-Function)  一进一出

    1.创建一个Maven工程Hive
    2.导入依赖
    <dependencies>
            <!-- https://mvnrepository.com/artifact/org.apache.hive/hive-exec -->
            <dependency>
                <groupId>org.apache.hive</groupId>
                <artifactId>hive-exec</artifactId>
                <version>1.2.1</version>
            </dependency>
    </dependencies>
    3.创建一个类
    
    4.打成jar包上传到服务器/opt/module/jars/udf.jar
    5.将jar包添加到hive的classpath
    hive (default)> add jar /opt/module/datas/udf.jar;
    6.创建临时函数与开发好的java class关联
    hive (default)> create temporary function mylower as "com.atguigu.hive.Lower";
    7.即可在hql中使用自定义的函数strip 
    hive (default)> select ename, mylower(ename) lowername from emp;

    也可创建永久UDF
    上传jar
    using JAR//hdfs上

  • 相关阅读:
    GX转账站点无法访问的问题

    .NET易忘备留 ORACLE存储过程调用
    Oracle 字符串函数
    Oracle 数值函数
    AJAX.JSONP 跨域
    机器人部署的注意事项
    IE6、7绝对定位层被遮挡的原因(主要是父层决定的)
    Oracle 新手问答
    字符设备驱动范例
  • 原文地址:https://www.cnblogs.com/shengyang17/p/10387448.html
Copyright © 2011-2022 走看看