将行扩展为presto

时间:2018-06-21 16:47:54

标签: presto

有什么方法可以有效地将行有效地扩展为列?

Problem

我尝试分别用'where team = 1'和'where team = 2'过滤原始数据集,以首先分别获取数据集1和数据集2,然后在收入级别上将两个数据集合并。但是,当income_level具有太多不同值时,这很不方便。有什么有效的方法来获得我想要的结果吗?

1 个答案:

答案 0 :(得分:1)

Prestodb提供了一个map_agg函数,可以帮助您将长数据转换为所需的宽格式。不幸的是,似乎没有一种动态创建列名的方法,但是这种方法应该比加入每个团队更有效(并且输入更少:)。

WITH raw_data AS (
  SELECT 1 AS team, 'a' AS income_level, 1 AS time, 11 AS ord
  UNION
  SELECT 1 AS team, 'b' AS income_level, 2 AS time, 12 AS ord
  UNION
  SELECT 1 AS team, 'c' AS income_level, 3 AS time, 13 AS ord
  UNION
  SELECT 2 AS team, 'a' AS income_level, 4 AS time, 14 AS ord
  UNION
  SELECT 2 AS team, 'b' AS income_level, 5 AS time, 15 AS ord
  UNION
  SELECT 2 AS team, 'c' AS income_level, 6 AS time, 16 AS ord
  UNION
  SELECT 3 AS team, 'a' AS income_level, 7 AS time, 17 AS ord
  UNION
  SELECT 3 AS team, 'b' AS income_level, 8 AS time, 18 AS ord
  UNION
  SELECT 3 AS team, 'c' AS income_level, 9 AS time, 19 AS ord
)

SELECT
  income_level,
  team_time[1] AS time_1,
  team_ord[1] AS ord_1,
  team_time[2] AS time_2,
  team_ord[2] AS ord_2,
  team_time[3] AS time_3,
  team_ord[3] AS ord_3
FROM (
  SELECT
    income_level,
    map_agg(team, time) AS team_time,
    map_agg(team, ord) AS team_ord
  FROM raw_data
  GROUP BY income_level
);

输出:

| income_level | time_1 | ord_1 | time_2 | ord_2 | time_3 | ord_3 |
|--------------|--------|-------|--------|-------|--------|-------|
| a            | 1      | 11    | 4      | 14    | 7      | 17    |
| b            | 2      | 12    | 5      | 15    | 8      | 18    |
| c            | 3      | 13    | 6      | 16    | 9      | 19    |

This site提供了另一个示例。