计算每个元素SQL

时间:2016-10-13 11:12:43

标签: sql data-manipulation postgresql-9.5

我需要在我的数据集上执行一个简单的计算:

refalt
 AA
 AT
 AC
 ...

我使用此SQL语句来检索我的信息:

select 
refalt,
count(*) as Total,
((
select 
count(*)
from ft_variant
where refalt IN ('AC','AT', 'AA')
)::numeric --Number of times that a couple is in
/
(
select count(*) 
from ft_variant
))as Frequency --Divided by total umber of elements
from ft_variant
group by refalt;

除了一件事,我的结果非常好:

   Refalt       Total   Frequency
    AC          131682  0.12
    AT          149385  0.12
    AA          55841   0.12

频率仅指AA,我想计算每对夫妇的频率。

reult应该是:

   Refalt       Total   Frequency
    AC          131682  0.20
    AT          149385  0.68
    AA          55841   0.12

有些东西不行我想不出来。

2 个答案:

答案 0 :(得分:1)

你太复杂了:

select refalt, 
       count(*) as total, 
       count(*)::numeric / (select count(*) from ft_variant) as frequency
from ft_variant
group by refalt

如果您想将其限制为'AC','AT', 'AA',可以在where子句中添加。{/ p>

答案 1 :(得分:1)

您正在计算“AC'”的百分比。 +' AT' +' AA'在表中。您想要计算您正在显示的一个重新形成的百分比。

大概:

select 
  refalt,
  count(*) as total,
  count(*)::numeric / sum(count(*)) over () as frequency
from ft_variant
where refalt in ('AC', 'AT', 'AA')
group by refalt;

这只关注AC' AC' AT'' AA'记录并给出每个重新计算的计数及其在该集合中的百分比。