2016-07-19 78 views
0

我目前有一個accounts表和一個account_activity表。 accounts表的相關列爲id。在account_activity表中,我有id,account_id,action_nameoccured列。每次登錄的用戶數量每週計數

我希望能夠繪製的多少用戶登錄的0次,1次,2次,n次在給定時間內的圖形(可以說WHERE occured BETWEEN now() AND now() - interval '1 week'

據我得到的選擇每個用戶登錄,使用下面的查詢量:

SELECT 
    a.id, 
    count(aa.*) AS logins 
FROM 
    account a 
LEFT JOIN 
    account_activity aa 
ON 
    a.id = aa.account_id AND 
    aa.action_name = 'logIn' 
GROUP BY 
    a.id 

這返回的id S和logins計數的列表。現在,我要選擇具有登錄每個帳戶數高於n被歸類爲n,所以:

SELECT 
    a.id, 
    LEAST(count(aa.*), 10) AS logins 
FROM 
    account a 
LEFT JOIN 
    account_activity aa 
ON 
    a.id = aa.account_id AND 
    aa.action_name = 'logIn' 
GROUP BY 
    a.id 

在這種情況下,logins永遠不會(查詢10)高於n。完全是我想要的方式。但結果現在需要我手動遍歷所有行,將它們插入到一個臨時對象,並增加從0每個鍵的計數n其中row['logins'] == key

我想獲得這樣的結果:

| logins | count | 
|--------|-------| 
|  0 | 10 | 
|  1 | 130 | 
|  2 | 14 | 
| ... | ... | 
|  n | 1830 | 

我不知道我怎麼會能夠做到這一點在PGSQL

+0

我已經閱讀了這3次,並且無法在給定的時間範圍要求中通過0次,1次,2次,n次登錄的_how多個用戶。需求中還有其他的東西嗎? –

+0

我希望能夠看到有多少用戶處於活動狀態。如果有人在上週內登錄了10次,該人員非常活躍。如果有人本週沒有登錄,那麼這個人是不活躍的。 –

回答

0

這是我從這個問題的理解:

select logins, count(*) as users 
from (
    select count(*) as logins 
    from account_activity aa 
    where action_name = 'logIn' 
    group by account_id 
) 
group by logins 
order by logins 
+0

您將錯過0登錄帳戶。 – NovaDenizen

0
SElECT q2.logins as logins, count(*) AS num_users FROM 
(
    SELECT sq.account_id AS account_id, sum(sq.login_count) AS logins FROM (
     (SELECT account_id, 1 AS login_count FROM 
      account_activity WHERE action_name = 'login') 
     UNION ALL 
     (SELECT id AS account_id, 0 AS login_count FROM accounts) 
    ) AS sq 
    GROUP BY account_id 
) AS q2 
GROUP BY q2.logins;