【大数据面试题】38 说说 Hive 怎么行转列

一步一个脚印,一天一道大数据面试题
博主希望能够得到大家的点赞收藏支持!非常感谢

点赞,收藏是情分,不点是本分。祝你身体健康,事事顺心!

行转列

假设我们有一张名为 sales_data 的表,其中包含 product_id(产品 ID)、category(类别)和 sales_amount(销售金额)这几列的数据。

步骤:

  1. group by id
  2. 聚合函数sum/max/min,里面套一个 if / case when
  3. as 列名

样例数据:

sql 复制代码
-- 样例 SQL
SELECT * FROM students;
+-----------+------------+-------------+
| stu_id    | subject    | score       |
+-----------+------------+-------------+
| 1         | Chinese    | 80          |
| 1         | Math       | 70          |
| 1         | English    | 75          |
| 2         | Chinese    | 77          |
| 2         | Math       | 60          |
| 2         | English    | 80          |
+-----------+------------+-------------+

开始行转列:

sql 复制代码
SELECT stu_id,
       SUM(IF(subject = 'Chinese', score, 0) AS chinese_score),
       SUM(IF(subject = 'Math', score, 0) AS math_score),
       SUM(IF(subject = 'English', score, 0) AS english_score)
FROM students
GROUP BY stu_id;

+-----------+--------------+-------------+---------------+
| stu_id    | chinese_score| math_score  | english_score |
+-----------+--------------+-------------+---------------+
| 1         | 80           | 70          | 75            |
| 2         | 77           | 60          | 80            |
+-----------+--------------+-------------+---------------+

我是近未来,祝你变得更强!

相关推荐
zhou_gai1 小时前
供应链计划 - 物料分类
大数据·分类·制造
BD_Marathon2 小时前
java.io.FileNotFoundException: File does not exist: hdfs://master:9000/sparklog
大数据·hadoop·hdfs
2501_941870562 小时前
人工智能与未来的工作:自动化与人类协作的新时代
大数据·人工智能
sunxunyong3 小时前
flink/spark/hive 使用paimon
hive·flink·spark
杜斯{Data}3 小时前
Excel 高阶实战:从脏数据到可视化报告的完整闭环
大数据·数据分析·excel
howard20053 小时前
5.4 Hive删除数据实战
hive·删除数据
无级程序员3 小时前
datasophon安装hive3.1.3手记
大数据·hive
大任视点7 小时前
科技赋能健康未来,守护生命青春活力
大数据·人工智能·科技
hans汉斯8 小时前
基于改进YOLOv11n的无人机红外目标检测算法
大数据·数据库·人工智能·算法·yolo·目标检测·无人机
励志成为糕手8 小时前
Flume架构深度解析:构建高可用大数据采集系统
大数据·架构·flume·日志·大数据采集