Sql 如何计算配置单元表中人员之间协议的重叠百分比
假设我有一个调查,每个问题有4个可能的答案,被调查的人可以选择至少一个答案(允许多个答案)。我想计算每个问题每个答案,有多少人选择了这个答案。例如,如果我有配置单元表:Sql 如何计算配置单元表中人员之间协议的重叠百分比,sql,hive,hiveql,Sql,Hive,Hiveql,假设我有一个调查,每个问题有4个可能的答案,被调查的人可以选择至少一个答案(允许多个答案)。我想计算每个问题每个答案,有多少人选择了这个答案。例如,如果我有配置单元表: question_id | answer_id | person_id ------------------------------------- 1 | A | 1 1 | B | 1 1 |
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%
我真的被卡住了,在网上找不到任何能完成我所寻找的东西。任何帮助都将是惊人的 嗯。如果我理解正确,您希望选择某个特定问题/答案组合的人数除以选择该问题的人数。如果是的话,我想
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;
我不熟悉prestoDB,但下面是一个SQL脚本,它的结果与您发布的相同
2.0
是人数。您可能希望首先选择该项并将其存储在VARABLE中
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
此外,您还可以使用分析函数和大小(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;