【问题标题】:Postgresql : How to display an additional column after an aggregate functionPostgresql:如何在聚合函数之后显示附加列
【发布时间】:2020-12-10 21:07:21
【问题描述】:

我有两个表:用户和会话。

用户有列:用户名,id

会话有列:userid、lastactivityat、deleteat

我希望为每个用户提取具有最近“最后活动日期”会话的所有用户,然后过滤“最后活动日期”超过 x 天的用户。 “最后活动日期”是纪元格式和毫秒,这就是我必须进行一些转换计算的原因。

这是我当前的请求(x = 30)

select u.username, min(extract(epoch from now() - to_timestamp(lastactivityat/1000))/86400::int) as most_recent_inactivity_days 
from users as u 
  join sessions as s on s.userid=u.id 
where extract(epoch from now() - to_timestamp(lastactivityat/1000))/86400::int >= 30 
group by username 
order by username

现在我希望添加到我的请求的结果中:每个用户的 deleteat 列,但我的请求失败了:

select u.username, min(extract(epoch from now() - to_timestamp(lastactivityat/1000))/86400::int) as most_recent_inactivity_days, s.deleteat  
from users as u 
  join sessions as s on s.userid=u.id 
where extract(epoch from now() - to_timestamp(lastactivityat/1000))/86400::int >= 30 
group by username 
order by username

你能建议吗?

【问题讨论】:

    标签: postgresql join aggregate-functions min


    【解决方案1】:

    这是DISTINCT ON的情况:

    SELECT DISTINCT ON (u.username)
           u.username,
           extract(epoch from now() - to_timestamp(lastactivityat/1000))/86400::int AS most_recent_inactivity_days,
           s.deleteat  
    FROM users AS u 
       JOIN sessions AS s ON s.userid=u.id 
    WHERE extract(epoch from now() - to_timestamp(lastactivityat/1000))/86400::int >= 30
    ORDER BY u.username,
             extract(epoch from now() - to_timestamp(lastactivityat/1000))/86400::int;
    

    这个很好的查询还说明了为什么将时间戳保存为时间戳而不是整数更好;这样查询会简单得多。

    【讨论】:

      猜你喜欢
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多