【大数据面试题】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            |
+-----------+--------------+-------------+---------------+

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

相关推荐
LaughingZhu1 小时前
Product Hunt 每日热榜 | 2026-01-31
大数据·人工智能·经验分享·搜索引擎·产品运营
babe小鑫1 小时前
中专学历进入快消大厂终端销售岗位的可行性分析
大数据
samFuB1 小时前
【工具变量】区县5A级旅游景区DID数据集(2000-2025年)
大数据
百夜﹍悠ゼ1 小时前
数据治理DataHub安装部署
大数据·数据治理
wdfk_prog2 小时前
解决 `git cherry-pick` 引入大量新文件的问题
大数据·git·elasticsearch
洛阳纸贵3 小时前
JAVA高级工程师--Elasticsearch
大数据·elasticsearch·搜索引擎
TracyCoder1233 小时前
ElasticSearch内存管理与操作系统(二):深入解析 Circuit Breakers(熔断器)机制
大数据·elasticsearch·搜索引擎
外参财观4 小时前
从浏览器到“超级眼”:夸克的突围战
大数据
BYSJMG5 小时前
计算机毕设选题推荐:基于大数据的癌症数据分析与可视化系统
大数据·vue.js·python·数据挖掘·数据分析·课程设计
petrel20155 小时前
【Spark 核心内参】2026.1:JIRA vs GitHub Issues 治理模式大讨论与 4.2.0 预览版首发
大数据·spark