HIVE学习与实践(三):结合linux shell脚本按日期提取表,count,distinct,group by用法

例子

下面的例子create_everyday.sh是在bash 脚本里面嵌入 hive的代码,实现在bash下
直接运行脚本

create_everyday.sh 20110101 20110302

就可以统计把每天的信息提出来。

create_everyday.sh:

# file: create_everday.sh
#!/bin/sh 
# 确定时间范围 从startdate到enddate
source /home/hduser0539/.bash_profile
 start=`date +%s`


  if [[ -z $1 ]]; then
      #dateStr=`date +%Y-%m-%d -d "-1 day"`
      echo "No start_date input!!!"
      exit
  else
      startdate=$1
  fi
   if [[ -z $2 ]]; then
      #dateStr=`date +%Y-%m-%d -d "-1 day"`
      echo "No end_date input!!!\n"
      exit
  else
      enddate=$2
  fi
  datestr=${startdate};
 while [[ $datestr -le $enddate ]]
     do
     echo $datestr
     #--------------统计某一天我们关心的各断点的个数,写在表 mytable2--------------------

     hive -e "
     set mapred.job.queue.name=queue_****; 
     insert overwrite table mydb.mytable2 
     partition (rcd_date='${datestr}')
     select     
     count(distinct case when id like '123456' then pn end ) as    id_123456    ,
     count(distinct case when id like '123' then pn end ) as  id_123   ,   
     from 
     (select 
        distinct phone_number as pn, info_id as id
     from 
         mytable.app_event_log  t1  
     where concat(y,m,d)='${datestr}' 
     ) tb2;
     "
     #datestr=$(date -d "${datestr}" +%Y-%m-%d)
     #echo $datestr

         datestr=$(date -d "${datestr} +1 day" +%Y%m%d)
done
 end=`date +%s`
 echo "Total run time = $(($end-$start)) second."

首先我们看hive里面的内容:
用到了select嵌套 ,要从后往前看
1. 第二个select出的表被别名叫tb2,where后面是按日期分区来查。
2. 第一个select 从tb2 再找出id = 123456 ,id= 123的,用case来判断,然后count总数。 这样出来的值,才是触发的断点123456的个数(不同手机号的量) 。写成id_123456,id123的原因是 mydb.mytable2 的相应列字段。
3. 这样一一对应上,再insert mydb.mytable2

其次看shell脚本:
其一是年月日的日期怎么记,date命令的用法。
其二是用到while … done
其三,最后一行的 echo “Total run time = (( end-$start)) second.” 是为了算脚本跑完了需要多长时间。

你可能感兴趣的:(数据库相关,数据挖掘,linux脚本)