2017-08-25 117 views
1

我有被髮送daily領域,Postgres的查詢 - 找到開始和周結束之差,每週

total_user_count, sent_at

user_report

我試圖找到total new users per week,其被定義爲

difference in user count from the beginning of the week to the ending of the week.

我似乎遇到了問題,雖然制定此查詢,我有什麼是

SELECT DATE_TRUNC('day', sent_at AT TIME ZONE '+08') as date, total_user_count 
FROM user_state_report 
WHERE timestamptz_cmp(DATE_TRUNC('week', sent_at AT TIME ZONE '+08') , DATE_TRUNC('day', sent_at AT TIME ZONE '+08'))=0 
ORDER BY TIMESTAMP 

哪給我每週的總用戶數。但我想每週新註冊,而不是總數量

理想輸出:

Date [monday of the week X], users registered in this week 14-08-2017 300 21-08-2017 400

謝謝! :)

回答

1

你應該能夠用滯後函數做到這一點。喜歡的東西:

SELECT date, total_user_count - COALESCE(LAG(total_user_count) OVER(order by date),0) AS new_users_registered from 
(SELECT DATE_TRUNC('day', sent_at AT TIME ZONE '+08') as date, total_user_count 
FROM user_state_report 
WHERE timestamptz_cmp(DATE_TRUNC('week', sent_at AT TIME ZONE '+08') , DATE_TRUNC('day', sent_at AT TIME ZONE '+08'))=0 
ORDER BY sent_at) l 

BTW我改變了你的ORDER BY TIMESTAMP到ORDER BY sent_at,因爲我沒有undertstand如何你一個工作!

+0

非常感謝! :)像一個魅力工作 – Wboy

+0

我的榮幸。祝你有美好的一天 –

相關問題