【问题标题】:Calculate for each element SQL计算每个元素的 SQL
【发布时间】:2017-02-22 11:37:40
【问题描述】:

我需要对我的数据集进行简单的计算:

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,我想计算每一对的频率。

结果应该是:

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

出了点问题,我想不通。

【问题讨论】:

    标签: sql data-manipulation postgresql-9.5


    【解决方案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 子句中。

    【讨论】:

      【解决方案2】:

      您正在计算表格中“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'、'AT' 和 'AA' 记录,并为您提供每次 refalt 的计数及其在该集合中的百分比。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-14
        • 2016-05-22
        • 1970-01-01
        • 1970-01-01
        • 2014-09-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多