按分隔符分解列并使用拆分列名称的前缀作为值

问题描述 投票:0回答:1

我有一个包含以下聚合的表格

页面网址 hour01_访问量 hour02_访问量
abc.com
9000 9500
def.com
3000 2300

并且想像这样爆炸它

页面网址 小时 访问
abc.com
01 9000
abc.com
02 9500
def.com
01 3000
def.com
02 2300

我知道如何使用 Presto cross join unnest 来分解数组,但在这里我通过列本身的名称来分解列。不确定这是否可能?

sql presto unpivot
1个回答
0
投票

您可以使用经典方法,即对所有列使用

UNION ALL
运算符来反转枢轴操作

SELECT pageurl, 
       1             AS hour,
       hour01_visits AS visits
FROM tab
UNION ALL 
SELECT pageurl, 
       2             AS hour,
       hour02_visits AS visits
FROM tab
ORDER BY pageurl, hour

更聪明的选择可能是将列转换为单个数组,然后对其应用

UNNEST
操作,使用
WITH ORDINALITY
子句来收集有序 id。

SELECT tab.pageurl, hour, visits
FROM tab,
     UNNEST(ARRAY[hour01_visits, hour02_visits]) WITH ORDINALITY cte(visits, hour);

输出”:

页面网址 小时 访问
abc.com 01 9000
abc.com 02 9500
def.com 01 3000
def.com 02 2300

查看演示这里

© www.soinside.com 2019 - 2024. All rights reserved.