如何快速展平SQL表

时间:2016-06-09 22:42:25

标签: sql presto

我正在使用Presto。如果我有一个像这样的表:

ID    CATEGORY     VALUE
1      a           ...
1      b
1      c
2      a
2      b
3      b 
3      d
3      e
3      f

如果不为每个组合编写案例陈述,您将如何转换为以下内容?

ID      A     B    C    D    E    F
1
2
3

2 个答案:

答案 0 :(得分:2)

我从未使用过Presto而且文档看起来很薄,但基于this article看起来你可以做到

SELECT
  id,
  kv['A'] AS A,
  kv['B'] AS B,
  kv['C'] AS C,
  kv['D'] AS D,
  kv['E'] AS E,
  kv['F'] AS F
FROM (
  SELECT id, map_agg(category, value) kv
  FROM vtable
  GROUP BY id
) t

虽然我建议尽可能在显示层执行此操作,因为您必须指定列。大多数报表工具和UI网格都支持某种动态透视,它将根据源数据创建列。

答案 1 :(得分:0)

我的2美分:

如果您知道“可能”的值:

SELECT 
    m['web'] AS web,
    m['shopping'] AS shopping,
    m['news'] AS news,
    m['music'] AS music,
    m['images'] AS images,
    m['videos'] AS videos,
    m[''] AS empty 
FROM (
SELECT histogram(data_tab) AS m
FROM datahub
WHERE
    year = 2017
    AND month = 5
    AND day = 7
    AND name = 'search'
) searches

没有PIVOT功能(还)!