postgresql 供应商分组依据和填充外键函数

r55awzrz  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(1)|浏览(153)

我在餐厅订了两桌:
用户:

uuid, name, created_at

字符串
留言内容:

uuid, text, created_at, created_by (foreign key to users.uuid)


我想做的是一个函数,返回最近24小时内最活跃的10个成员。所以我想在消息表中分组和计数created_by,完成后我想获取用户的真实的名称,而不是指向用户的外键created_by。uuid

qkf9rpyu

qkf9rpyu1#

如果名称是唯一的

select users.name,count(*)
from messages join users on messages.created_by=users.uuid
where messages.created_at>=now()-'24h'::interval
group by 1 order by 2 desc limit 10;

字符串
否则

select users.name,a.count from
(   select created_by,count(*)
    from messages
    where messages.created_at>=now()-'24h'::interval
    group by 1 order by 2 desc limit 10 ) a
join users on a.created_by=users.uuid order by 2 desc;


如果你真的需要一个函数,你可以将语句 Package 在一个:

create function top_10_chatters_24h()
returns table (name text,count bigint) as $f$
select users.name,a.count from
(   select created_by,count(*)
    from messages
    where messages.created_at>=now()-'24h'::interval
    group by 1 order by 2 desc limit 10 ) a
join users on a.created_by=users.uuid order by 2 desc; 
$f$ language sql;

select * from top_10_chatters_24h();


Demo at db<>fiddle

相关问题