如何计算hive表中人与人之间一致的重叠百分比

px9o7tmv  于 2021-04-21  发布在  Hive
关注(0)|答案(3)|浏览(683)

假设我有一个调查,每个问题有4个可能的答案,被调查者至少可以选择一个答案(允许多个答案)。我想计算每个问题的每个答案,有多少人选择这个答案。例如,如果我有hive表。

question_id | answer_id | person_id
-------------------------------------
1           | A         |    1        
1           | B         |    1        
1           | C         |    1        
1           | D         |    1        
1           | A         |    2        
1           | B         |    2        
1           | C         |    2        
2           | D         |    1        
2           | A         |    1

那么得出的表格将是。

question_id | answer_id | Percentage
-------------------------------------
1           | A         |    100        
1           | B         |    100       
1           | C         |    100        
1           | D         |    50
2           | D         |    50        
2           | A         |    50

对于问题1,两个人都填了a,b,c,这三个答案都是100%,但有一个人也填了d,占50%。对于问题2,一个人填了d,一个人填了a,占50%和50%。
我真的被卡住了,我没能在网上找到任何能实现我所寻找的东西。任何帮助都是惊人的!

aurhwmvo

aurhwmvo1#

你也可以使用分析函数和size(collect_set)来计算不同的人。这将允许消除连接,并且如果每个问题的不同人的数量不是太大的话(collect_set产生的数组可以容纳在内存中),就可以正常工作。

select qa.question_id, qa.answer_id, 
       qa.num_persons * 100.0 / size(qa.question_persons) as Percentage
from (select question_id, answer_id, 
             count(*) over (partition by question_id, answer_id) as num_persons,
             collect_set(person_id) over(partition by question_id) as question_persons
      from t
     ) qa;
szqfcxe2

szqfcxe22#

如果我理解正确的话,你想要选择某个特定问题/答案组合的人数除以选择该问题的人数。

select qa.*, qa.num_persons * 100.0 / q.num_persons
from (select question_id, answer_id, count(*) as num_persons
      from t
      group by question_id, answer_id
     ) qa join
     (select question_id, count(distinct person_id) as num_persons
      from t
      group by question_id
     ) q
     on qa.question_id = q.question_id;
5gfr0r5j

5gfr0r5j3#

我对prestodb不熟悉,但下面是一个sql脚本,它的结果与你发布的内容相同。
`2.0'是人的数量。你可能想先选择它,然后把它存储在一个可移动的容器中。

select 
     question_id, answer_id, (count(answer_id)/2.0) * 100.0
from Sample
group by question_id, answer_id
order by question_Id, answer_id

相关问题