当前位置: 首页 > article >正文

HiveSQL——借助聚合函数与case when行转列

一、条件函数

if 条件函数

   if函数是最常用到的条件函数,其写法是if(x=n,a,b),  x=n代表判断条件,如果x=n时,那么结果返回a ,否则返回b。

select
    if(age < 25 or age is null, '25岁以下', '25岁以上') as age_cnt,
    count(1)  as number
from table1
group by age_cnt;

case when

case when 与if的作用基本相同,也是按照条件更换列中的内容,区别是case when 可以对 多个条件进行转换,需要注意的是:结尾需要加end作为结束标志

case 测试表达式
when 简单表达式1 then 结果表达式1
when 简单表达式2 then 结果表达式2
.......

when 健达表达式n then 结果表达式n
[else 结果表达式 n+1]
end
--举例:
select case when age <25 or age is null then '25岁以下'
             else '25岁及以上'
             end as  age_cnt,
count(1) as  number
from table1 
group by age_cnt;

-- 举例:
select device_id,
       gender,
  case when age<20 then '20岁以下'
       when age>=20 and age<=24 then '20-24岁'
       when age>=25 then '25岁及以上'
       else '其他'
       end as age_cut
from table1;

二、运用案例

2.1 行转列

问题描述

   

数据准备

 create table if not exists test
    (
        col1   string comment '',
        col2   string comment '',
        col3    string comment ''
    ) comment '测试表';

    insert overwrite table test
    values ('a','g','11'),
           ('a','f','23'),
           ('a','d','9'),
           ('b','g','5'),
           ('b','f','8'),
           ('b','d','47');

数据分析

利用case  when 进行行转列

select
    col1,
    case col2 when 'g' then col3 else 0 end as g,
    case col2 when 'f' then col3 else 0 end as f,
    case col2 when 'd' then col3 else 0 end as d
from test;

 

 最后,分组求max值即可

select
    col1,
    max(case col2 when 'g' then col3 else 0 end) as g,
    max(case col2 when 'f' then col3 else 0 end) as f,
    max(case col2 when 'd' then col3 else 0 end) as d
from test
group by col1;

 最终的输出结果:

小结


http://www.kler.cn/news/234032.html

相关文章:

  • 【Java】案例:检测MySQL是否存在某数据库,没有则创建
  • DC-8靶机渗透详细流程
  • 怎么用postman调用webservice(反推SoapUI)
  • Ubuntu上开启SFTP服务教程
  • 软件安全测试报告如何编写?权威的安全测试报告如何获取?
  • Hive-架构与设计
  • CNN应用Keras Tuner寻找最佳Hidden Layers层数和神经元数量
  • vue3跨组件(多组件)通信:事件总线【Event Bus】
  • 修改GI文件的权限
  • 双活工作关于nacos注册中心的数据迁移
  • C#系列-C#访问MongoDB+redis+kafka(7)
  • Avalonia学习(二十三)-大屏
  • 方格定位2_题解
  • Qt安装配置教程windows版(包括:Qt5.8.0版本,Qt5.12,Qt5.14版本下载安装教程)(亲测可行)
  • STM32 FSMC (Flexible static memory controller) 灵活静态内存控制器介绍
  • Android java基础_类的继承
  • python如何用glob模块匹配路径
  • Lua Global环境
  • 时间序列预测——BiGRU模型
  • 应急响应-挖矿木马-常规处置方法
  • notepad++成功安装后默认显示英文怎么设置中文界面?
  • 突破编程_C++_面试(基础知识(10))
  • 学习笔记——ENM模拟
  • 微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流
  • 零基础学编程从入门到精通,系统化的编程视频教程上线,中文编程开发语言工具构件之缩放控制面板构件用法
  • Centos 7系统安装proftpd-1.3.8过程
  • 图像的旋转不变特性及应用
  • React18原理: Fiber架构下的单线程CPU调度策略
  • 代码随想录-背包问题
  • vue3 之 商城项目—详情页