2. SQL中的透视表 (枢纽表、pivot table)

SQL中的透视表 (枢纽表、pivot table)

定义

枢纽表(英语:pivot table)也翻译成透视表,是用来汇总其它表的数据。首先把源表分组(grouping),然后对各组内数据做汇总操作如排序、平均、累加、计数或字符串连接等。透视表用于数据处理,在数据可视化程序如电子表格商业智能软件中常见。

举例:

  1. 一张表包含一列数;透视表仅含一行一列为源表该列的均值。
  2. 源表有两列分别为 “性别“ 与 “身高” ,表的每行给出一个人的性别与高度;透视表有两行两列,在 “性别” 列分别写 “男性” 与 “女性” ,在 “身高” 列分别写对应性别的平均身高。
案例实现
案例1:

写一个查询语句实现对大洲(continent)列的 透视表 操作,使得每个学生按照姓名的字母顺序依次排列在对应的大洲下面。输出的标题应依次为美洲(America)、亚洲(Asia)和欧洲(Europe)。

-- 源数据
with student as (
    select 'Jack' as name, 'America' as continent
    union all
    select 'Pascal' as name, 'Europe' as continent
    union all
    select 'Xi' as name, 'Asia' as continent
    union all
    select 'Jane' as name, 'America' as continent
)

-- 查询 源表数据
-- select * from student;

--    输出结果
-- name    continent
-- Jack		America
-- Xi		Asia
-- Pascal	Europe
-- Jane		America

--  查询语句
-- 使用max() 是因为 group之后需要使用聚合函数
select max(if(continent = 'America', name, null)) America,
       max(if(continent = 'Asia', name, null))    Asia,
       max(if(continent = 'Europe', name, null))  Europe
from (select *, row_number() over (partition by continent order by name) rk
      from student) t
group by rk;

--    输出结果
-- america     asia    europe
-- Jack        Xi      Pascal
-- Jane        NUll    NULL
案例2:
-- 实际工作当中遇到这样一个问题,数据如下。我想通过SQL将数据转换成按列展示的形式,即常用的pivot透视操作。

-- # 原始数据
-- id item value
-- 2,   b,  21
-- 1,   b,  15
-- 2,   a,  20
-- 1,   a,  10

-- # 次级目标格式(SQL)
-- id     item     Value
-- 2,   item-a,     20
-- 2,   item-b,     21
-- 1,   item-a,     10
-- 1,   item-b,     15

-- # 目标格式
-- id  item_a  item_b
-- 1,   10,     15
-- 2,   20,     21
-- 查询 源表数据
-- select * from test;

--    输出结果
-- id   item    value
-- 1     b      15
-- 2     b      21
-- 1     a      10
-- 2     a      20

--  查询语句

-- 2)目标格式
select id,
       max(if(item_col = 'item-a', value, null)) as item_a,
       max(if(item_col = 'item-b', value, null)) as item_b
from (
        -- 1) 次级目标格式(SQL)
         select id,
                concat('item-', item) as item_col,
                value
         from test
     ) t1
group by id;
学习链接

维基百科 - 透视表

hive-sql中透视表的实现

Hive当中实现pivot操作

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dataer__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值