Postgres查询 - 查找每周开始和结束之间的差异

时间:2017-08-25 03:22:11

标签: sql postgresql

我有一个带有字段

的列user_report

total_user_count, sent_at

发送的内容daily

我正在尝试找到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 个答案:

答案 0 :(得分: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,因为我没有理解你的工作方式!