如何处理多个重叠的数据集?

时间:2019-04-05 17:58:06

标签: sql hadoop hive

我有一组结构如下的数据:

[user_id, title, country, platform, language]
[100, 'Title A', 'US', 'Windows', 'English']
[100, 'Title A', 'US', 'Android', 'English']
[200, 'Title C', 'FR', 'Windows', 'French']
[300, 'Title B', 'US', 'Windows', 'English']
And so on...

我需要转换这些数据,以便计算每个类别中唯一的用户数。

如果我要编写查询:

SELECT
title
, country
, platform
, language
count(distinct user_id)
FROM table
GROUP BY 1
, 2
, 3
, 4

结果表如下:

[title, country, platform, language, unique_count]
['Title A', 'US', 'Windows', 'English', 10,000]
['Title A', 'US', 'Android', 'English', 7,000]
['Title C', 'FR', 'Windows', 'France', 4,000]
['Title B', 'US', 'Windows', 'English', 8,000]
And so on...

如果我要隔离各个维度,则由于用户可能属于多个类别,因此会有重叠。

我如何以包含行并且可以在仪表板中列出行的方式构造数据?

如果只有两个类别,这似乎是一个更简单的问题,因为数据可以格式化为多维数据集:

        | Windows | Android |
--------+---------+---------+----
Title A | 10,000  |  7,000  | 17,000
--------+---------+---------+----
Title B |  8,000  |  11,000 | 19,000
--------+---------+---------+----
        | 19,000  | 18,000  |

是否存在可能包含所有维度的类似n维结构的东西?

另一个问题是数据必须聚合并且不能因为大小太大而无法存储在内存中。

1 个答案:

答案 0 :(得分:0)

如果需要所有组合,请使用with cube

SELECT title, country, platform, language,
       count(unique user_id)
FROM table
GROUP BY title, country, platform, language with cube;

更常见的是,我更喜欢GROUPING SETS。例如,要获取所有对:

SELECT title, country, platform, language,
       count(unique user_id)
FROM table
GROUP BY ( (title, country),
           (title, platform),
           (title, language),
           (country, platform),
           (country, language),
           (platform, language)
         );
相关问题