【问题标题】:How to know my progress with others progress using SQL如何使用 SQL 了解我与他人的进度
【发布时间】:2020-10-17 02:10:21
【问题描述】:

我有下表

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 与表中其他用户的进度比较。 用户:4 取得了 10% 的进步,是否可以从全局的角度在表格中了解他的进步与其他人的进步? 这是为了知道他与其他用户相比落后或领先多远。

谢谢。

【问题讨论】:

  • 你不知道Select user, progress from run_progress 吗?
  • @sri User:4 完成进度是 10% 但如何知道他的排名?
  • @Eric 。 . .请显示您想要的结果。您的描述不明确。
  • @GordonLinoff 如何知道用户:4 排名。因为他只完成了 10%,所以他的排名应该是 4。用户:2 排名应该是 90,用户:1 排名应该是 1。

标签: sql postgresql compare percentage


【解决方案1】:

您可以在一行中汇总和比较汇总统计信息:

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

【讨论】:

  • 这为用户 1 提供了 95%。但实际上 user:1 已经完成了 100%,所以应该是 100%。我不认为这个查询对我有用。
  • @Eric 。 . .你能设置一个数据库小提琴吗?我认为这不可能为用户 1 返回 95%。
【解决方案2】:

窗口总和不适合您的需要吗?

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

【讨论】:

  • 对于任何用户,这个查询给我 66.6666666666667,我认为它不正确
猜你喜欢
  • 1970-01-01
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多