2017-08-04 63 views
0

我正在嘗試計算首次登錄到網站的有多少個不同且唯一的user_ID。以下是SQL查詢,它根據在網站上的first_hit條件來計算不同的user_ID。但我不確定同一用戶是否在不同的日子登錄。一個用戶登錄應該只計算一次(唯一)。在postgresql中每天計算不同且獨特的用戶登錄數

我寫的第一個查詢:

select 
    --'Jan 2017' as month, 
    to_char(first_hit_at::date,'dd-mm-yyyy') as date, 
    count(distinct a.user_id) as unique_user_logins_in_month 
from 
     stg_marketing.ga_sessions a 
where 
    a.first_hit_at >('2017-01-01 00:00:00.000') 
    and a.first_hit_at <('2017-02-01 00:00:00.000') 
    and user_login_state = 'true' 
    group by 1 
    order by 1 

其次,提高了查詢:

date  unique_user_logins_in_month 
    01-01-2017 97 
    02-01-2017 96 
    03-01-2017 62 
    04-01-2017 61 
    05-01-2017 69 

date   unique_user_logins_in_month 
01-01-2017 7008 
02-01-2017 11023 
03-01-2017 10318 
04-01-2017 10091 
05-01-2017 8726 

查詢兩種結果:

select 
    --'Jan 2017' as month, 
    to_char(first_hit_at::date,'dd-mm-yyyy') as date, 
    count(distinct a.user_id) as unique_user_logins_in_month 
from 
    stg_marketing.ga_sessions a 
where 
    a.first_hit_at >('2017-01-01 00:00:00.000') 
    and a.first_hit_at <('2017-02-01 00:00:00.000') 
    and user_login_state = 'true' 
    and last_hit_at::date > first_hit_at::date 
    group by 1 
    order by 1 

查詢一個結果

我不確定這兩個查詢是否正確或第二個更正確。謝謝

+0

我不不明白「但我不確定同一用戶是否在不同的日子登錄」,爲什麼你關心用戶是否在第二天登錄? 'first_hit_at'是你第一次看到用戶的權利? 。你可以發佈表結構嗎? –

+0

@AkliREGUIG我添加了兩個查詢和兩個輸出結果。你可以看看現在嗎?謝謝 –

+0

如果沒有桌子的結構和限制,我不禁感慨。你用什麼工具/ ETL將GA數據推送到postgres中? –

回答

0

第一個登錄網站的第一個 時間有多少個截然不同的用戶標識。

如果用戶以前從未登錄過,則該用戶是第一次登錄。
您可以登錄使用NOT EXISTS操作此類用戶的條目(這就是所謂的ANTI JOIN):

select * 
from 
     stg_marketing.ga_sessions a 
where 
    a.first_hit_at >('2017-01-01 00:00:00.000') 
    and a.first_hit_at <('2017-02-01 00:00:00.000') 
    and user_login_state = 'true' 
    AND NOT EXISTS (
     select * from stg_marketing.ga_sessions b 
     where a.user_id = b.user_id 
      and b.first_hit_at < a.first_hit_at 
    ) 

現在只是做上述查詢結果的聚合

select 
    to_char(first_hit_at::date,'dd-mm-yyyy') as date, 
    count(distinct a.user_id) as unique_user_logins_in_month 
from 
     stg_marketing.ga_sessions a 
where 
    a.first_hit_at >('2017-01-01 00:00:00.000') 
    and a.first_hit_at <('2017-02-01 00:00:00.000') 
    and user_login_state = 'true' 
    AND NOT EXISTS (
     select * from stg_marketing.ga_sessions b 
     where a.user_id = b.user_id 
      and b.first_hit_at < a.first_hit_at 
    ) 
group by to_char(first_hit_at::date,'dd-mm-yyyy') 
相關問題