如何知道我和别人的进展使用sql进展

nwwlzxa7  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(273)

我有一张table

CREATE TABLE run_progress
(
   id INT PRIMARY KEY,
   user varchar(255),
   progress numeric
)

INSERT INTO run_progress ( id, user, progress ) VALUES ( 1, 1, 100 )
INSERT INTO run_progress ( id, user, progress ) VALUES ( 2, 2, 90 )
INSERT INTO run_progress ( id, user, progress ) VALUES ( 3, 3, 60 )
INSERT INTO run_progress ( id, user, progress ) VALUES ( 4, 4, 10 )

我想知道user:4 progress 与表中的其他用户进行比较。user:4 made 一个10%的进度,有没有可能知道他的进度与其他人的进度相比,在表中以全局的观点来看?这是为了知道他比其他用户落后或前进了多远。
谢谢您。

t9aqgxwy

t9aqgxwy1#

您可以在一行中聚合和比较摘要统计信息:

select max(progress) filter (where id = 4) as user_4,
       min(progress) filter (where id <> 4) as min_other_users,
       max(progress) filter (where id <> 4) as max_other_users,
       avg(progress) filter (where id <> 4) as avg_other_users
from run_progress p
zte4gxcn

zte4gxcn2#

一笔小额贷款不符合你的需要吗?

select *
from (
    select 
        p.*, 
        avg(progress) filter(where id <> 4) over() avg_progress_of_other_users
    from run_progress p
) p
where id = 4

如果希望同时对所有用户(而不仅仅是一个特定用户)执行此操作,则横向联接更适合:

select p.*, a.*
from run_progress p
left join lateral (
    select avg(p1.progress) avg_progress_of_other_users
    from run_progress p1    
    where p1.id <> p.id
) a on true

相关问题