Postgresql:如何在聚合函数之后显示附加列
Posted
技术标签:
【中文标题】Postgresql:如何在聚合函数之后显示附加列【英文标题】:Postgresql : How to display an additional column after an aggregate function 【发布时间】: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
你能建议吗?
【问题讨论】:
【参考方案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;
这个很好的查询还说明了为什么将时间戳保存为时间戳而不是整数更好;这样查询会简单得多。
【讨论】:
以上是关于Postgresql:如何在聚合函数之后显示附加列的主要内容,如果未能解决你的问题,请参考以下文章
Postgresql 错误:列必须出现在 GROUP BY 子句中或在聚合函数中使用
Django 与 Postgresql,列必须出现在 GROUP BY 子句中或在聚合函数中使用