Postgresql:如何在聚合函数后显示其他列

问题描述

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

用户具有列:用户名,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

请您指教吗?

解决方法

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;

这个很好的查询还显示了为什么最好将时间戳记保存为时间戳而不是整数。这样查询就会简单得多。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...