PostgreSQL 中的 DATE ADD 函数

DATE ADD function in PostgreSQL

我目前在 Microsoft SQL 服务器中有以下代码来获取连续两天查看的用户。

WITH uservideoviewvideo (date, user_id) AS (
  SELECT  DISTINCT date, user_id 
  FROM clickstream_videos
  WHERE event_name ='video_play'  
    and user_id IS NOT NULL
) 
SELECT currentday.date AS date, 
       COUNT(currentday.user_id) AS users_view_videos, 
       COUNT(nextday.user_id) AS users_view_next_day 
FROM userviewvideo currentday
  LEFT JOIN userviewvideo nextday 
         ON currentday.user_id = nextday.user_id AND DATEADD(DAY, 1, 
currentday.date) = nextday.date
GROUP BY currentday.date

我试图让 DATEADD 函数在 Postgre 中工作SQL,但我一直无法弄清楚如何让它工作。有什么建议吗?

我不认为 PostgreSQL 真的有 DATEADD 函数。相反,只需执行:

+ INTERVAL '1 day'

SQL Server:

Add 1 day to the current date November 21, 2012
SELECT DATEADD(day, 1, GETDATE()); # 2012-11-22 17:22:01.423

PostgreSQL:

Add 1 day to the current date November 21, 2012
SELECT CURRENT_DATE + INTERVAL '1 day'; # 2012-11-22 17:22:01
SELECT CURRENT_DATE + 1; # 2012-11-22 17:22:01

http://www.sqlines.com/postgresql/how-to/dateadd

编辑:

如果您使用动态的时间长度来创建一个字符串,然后将其转换为一个间隔,这可能会很有用,例如:

+ (col_days || ' days')::interval

您可以使用 date + 1 来执行与 dateadd() 相同的操作,但我认为您的查询无法满足您的要求。

您应该使用 window 函数,而不是:

with plays as (
  select distinct date, user_id
    from clickstream_videos
   where event_name = 'video_play' 
     and user_id is not null
), nextdaywatch as (
  select date, user_id, 
         case
           when lead(date) over (partition by user_id
                                     order by date) = date + 1 then 1
           else 0
         end as user_view_next_day
    from plays
)
select date, 
       count(*) as users_view_videos,
       sum(user_view_next_day) as users_view_next_day
  from nextdaywatch
 group by date
 order by date;