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

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

一、条件函数

if 条件函数

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

selectif(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 testvalues ('a','g','11'),('a','f','23'),('a','d','9'),('b','g','5'),('b','f','8'),('b','d','47');

数据分析

利用case  when 进行行转列

selectcol1,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值即可

selectcol1,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.lryc.cn/news/298924.html

相关文章:

  • 冒泡排序,判断回文,以及12-24小时制
  • 【Vue】computed与watch
  • 探索设计模式的魅力:捕捉变化的风-用观察者模式提升用户体验
  • SpringCloud-高级篇(十九)
  • Junit常用断言
  • docker 实现 mysql:8.3.0 主从复制(2024年2月13日最新版本)
  • STM32 + ESP8266,连接阿里云 上报/订阅数据
  • 如何利用chatgpt提升工作效率?
  • MongoDB聚合:$geoNear
  • Docker-CE 国内源国内镜像
  • 【Tauri】(3):使用Tauri1.5版本,进行桌面应用开发,在windows上搭建环境,安装node,rust环境,可以打包成功,使用vite创建应用
  • C++ 堆排序
  • U3D记录之FBX纹理丢失问题
  • 监测Nginx访问日志502情况后并做相应动作
  • 【数据分享】1929-2023年全球站点的逐年平均风速(Shp\Excel\免费获取)
  • Android性能调优 - 应用安全问题
  • C#的Char 结构的像IsLetterOrDigit(Char)等常见的方法
  • 部分意图分类【LLM+RAG】
  • 1277. 统计全为 1 的正方形子矩阵
  • Python 3 时间序列可视化指南
  • [算法前沿]--059-大语言模型Fine-tuning踩坑经验之谈
  • 【Docker】01 Docker安装与配置
  • Unity3d Shader篇(六)— BlinnPhong高光反射着色器
  • Go-zero微服务个人探究之路(十二)定时任务的选择调研
  • Java中,List、Map和Set的区别是什么?
  • Google刚刚推出了图神经网络Tensorflow-GNN
  • 链表基础知识汇总
  • Educational Codeforces Round 2(远古edu计划)
  • 【Tauri】(1):使用Tauri1.5版本,进行桌面应用开发,在windows,linux进行桌面GUI应用程序开发,可以打包成功,使用 vite 最方便
  • 「Linux」软件安装