2015-11-04 59 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