How to Quickly Flatten a SQL Table

落花浮王杯 提交于 2019-12-22 08:57:10

问题


I'm using Presto. If I have a table like:

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

How would you convert to the below without writing a case statement for each combination?

ID      A     B    C    D    E    F
1
2
3

回答1:


I've never used Presto and the documentation seems pretty thin, but based on this article it looks like you could do

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

Although I'd recommend doing this in the display layer if possible since you have to specify the columns. Most reporting tools and UI grids support some sort of dynamic pivoting that will create columns based on the source data.




回答2:


My 2 cents:

If you know "possible" values:

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

No PIVOT function (yet)!



来源:https://stackoverflow.com/questions/37737358/how-to-quickly-flatten-a-sql-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!