【问题标题】:DATE ADD function in PostgreSQLPostgreSQL 中的 DATE ADD 函数
【发布时间】:2020-11-18 08:30:10
【问题描述】:

我目前在 Microsoft SQL Server 中有以下代码,用于获取连续两天查看的用户。

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 函数在 PostgreSQL 中工作,但我一直无法弄清楚如何让它工作。有什么建议吗?

【问题讨论】:

标签: postgresql date-arithmetic


【解决方案1】:

我不认为 PostgreSQL 真的有 DATEADD 功能。相反,只需这样做:

+ INTERVAL '1 day'

SQL 服务器:

2012 年 11 月 21 日的当前日期增加 1 天
SELECT DATEADD(day, 1, GETDATE()); # 2012-11-22 17:22:01.423

PostgreSQL:

2012 年 11 月 21 日的当前日期增加 1 天
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

【讨论】:

    【解决方案2】:

    您可以使用date + 1 来执行与dateadd() 等效的操作,但我认为您的查询不会执行您想要执行的操作。

    您应该改用窗口函数:

    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;   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      • 2020-04-23
      • 2014-01-28
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      相关资源
      最近更新 更多