2015-11-04 62 views
0

这是Postgres 8.x,特别是Redshift如何在单个表格上划分计数?

我有一张表,我查询返回一个单一的值,这是一个简单的除法操作的结果。桌上的谷物看起来像user_id | campaign_title

除法运算等行,其中CAMPAIGN_NAME是ilike %completed%由不同user_ids的计数除以计数。

所以我都写出来的分子和分母的查询,但我很诚实困惑如何将它们结合起来。

分子:

select count(*) as num_completed 
from public.reward 
where campaign_title ilike '%completion%' 
; 

分母:

select count(distinct(user_id)) 
from public.reward 

回答

1

直截了当的解决方案,只需将一个由其它:

select (select count(*) as num_completed 
     from public.reward 
     where campaign_title ilike '%completion%') 
     /
     (select count(distinct user_id) from public.reward); 

稍微更复杂,但更快的解决方案:

select count(case when campaign_title ilike '%completion%' then 1 end) 
    /
     count(distinct user_id) 
from public.reward; 

表达count(case when campaign_title ilike '%completion%' then 1 end)将只计算满足when子句中指定的条件的行。


无关,但:

distinct的功能。写作distinct(user_id)是无用的。和 - Postgres里的情况下 - 它实际上可以让你陷入困境,如果你保持distinct思想为功能,因为表达(column_one, column_2)比列的列表不同的东西在Postgres的:column_one, column_2

+0

感谢有关'distinct'珍闻。我想出了如何去做,实际上看起来和你的第二个建议很相似。 – simplycoding