HIVE Pivot и считать - PullRequest
       42

HIVE Pivot и считать

1 голос
/ 04 ноября 2019

У меня есть таблица, которую я пытаюсь выяснить, как поворачивать и рассчитывать на основе этих. Этот пример может быть не очень подходящим, но результат - именно то, что я хочу.

Пример ввода:

name |chinese|math|english
tom  |A      |A   |B
tom  |B      |A   |C
peter|B      |C   |C
peter|A      |B   |C

Пример вывода:

name |object |A|B|C
tom  |chinese|1|1|0
tom  |math   |2|0|0
tom  |english|0|1|1
peter|chinese|1|1|0
peter|math   |0|1|1
peter|english|0|0|2

1 Ответ

0 голосов
/ 04 ноября 2019

Используйте UNION ALL с агрегацией.

Демо:

with your_table as (
select stack(4,
'tom'  ,'A','A','B',
'tom'  ,'B','A','C',
'peter','B','C','C',
'peter','A','B','C'
) as (name,chinese,math,english)
)

select name, 'chinese' as object, 
       count(case when chinese='A' then 1 end) as A, 
       count(case when chinese='B' then 1 end) as B,
       count(case when chinese='C' then 1 end) as C
  from your_table 
 group by name
    UNION ALL 
select name, 'math' as object, 
       count(case when math='A' then 1 end) as A, 
       count(case when math='B' then 1 end) as B,
       count(case when math='C' then 1 end) as C
  from your_table 
 group by name
    UNION ALL 
select name, 'english' as object, 
       count(case when english='A' then 1 end) as A, 
       count(case when english='B' then 1 end) as B,
       count(case when english='C' then 1 end) as C
  from your_table 
 group by name;

Результат:

name    object  a       b       c
peter   chinese 1       1       0
tom     chinese 1       1       0
peter   math    0       1       1
tom     math    2       0       0
peter   english 0       0       2
tom     english 0       1       1
...