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

一、条件函数

if 条件函数

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

sql 复制代码
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作为结束标志

sql 复制代码
case 测试表达式
when 简单表达式1 then 结果表达式1
when 简单表达式2 then 结果表达式2
.......

when 健达表达式n then 结果表达式n
[else 结果表达式 n+1]
end
sql 复制代码
--举例:
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 行转列

问题描述

数据准备

sql 复制代码
 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 进行行转列

sql 复制代码
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值即可

sql 复制代码
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;

最终的输出结果:

小结

相关推荐
汽车仪器仪表相关领域1 小时前
全自动化精准检测,赋能高效年检——NHD-6108全自动远、近光检测仪项目实战分享
大数据·人工智能·功能测试·算法·安全·自动化·压力测试
大厂技术总监下海1 小时前
根治LLM胡说八道!用 Elasticsearch 构建 RAG,给你一个“有据可查”的AI
大数据·elasticsearch·开源
石像鬼₧魂石3 小时前
22端口(OpenSSH 4.7p1)渗透测试完整复习流程(含实战排错)
大数据·网络·学习·安全·ubuntu
TDengine (老段)3 小时前
TDengine Python 连接器进阶指南
大数据·数据库·python·物联网·时序数据库·tdengine·涛思数据
数据猿5 小时前
【金猿CIO展】如康集团CIO 赵鋆洲:数智重塑“顶牛”——如康集团如何用大数据烹饪万亿肉食产业的未来
大数据
zxsz_com_cn7 小时前
设备预测性维护的意义 工业设备预测性维护是什么
大数据
samLi06208 小时前
【数据集】中国杰出青年名单数据集(1994-2024年)
大数据
成长之路5148 小时前
【数据集】分地市旅游收入数据集(2000-2024年)
大数据·旅游
大厂技术总监下海9 小时前
用户行为分析怎么做?ClickHouse + 嵌套数据结构,轻松处理复杂事件
大数据·数据结构·数据库
大厂技术总监下海9 小时前
大数据生态的“主动脉”:RocketMQ 如何无缝桥接 Flink、Spark 与业务系统?
大数据·开源·rocketmq