简体   繁体   English

如何查询与其他列的聚合数据

[英]How to query aggregated data with other columns

Given is below record in user_score table where each user can have multiple score, user will diff user id can have same name and role.鉴于user_score表中的记录,每个用户可以有多个分数,用户将user_score用户 id 可以具有相同的名称和角色。 How to fetch average score along with user_id , role and name .如何获取平均分数以及user_idrolename I want to group by user_id .我想按user_id分组。

So for my below table I am expecting result as:所以对于我的下表,我期望结果为:

Name   Role  Score  user_id
Jack   CEO     6      123
Jack   CEO     2      456
Tony   Dev     5      234
Sham    QA     3      678

user_score table data : user_score 表数据:

id     name    role     score    user_id
1      Jack    CEO       4        123
2      Jack    CEO       8        123
3      Tony    Dev       9        234
4      Jack    CEO       2        456
5      Tony    Dev       1        234
6      Sham    QA        3        678

Simply use group by :只需使用group by

select id, name, role, avg(score), user_id
from user_score
group by id, name, role, user_id

PS: You can normalize the data because 3/5 columns are redundant (they're unnecessarily repeated). PS:您可以标准化数据,因为 3/5 列是多余的(它们不必要地重复)。 I would leave only score and user_id in this table, move user_id , role and name to the other and use user_id as a joining key.我只会在这个表中留下scoreuser_id ,将user_idrolename移动到另一个并使用user_id作为加入键。

While you might know that a given user_id always has the same name and role, PostgreSQL has no way of knowing that (other than you normalizing your data), so it needs instructions on what to report for more than one name within a given user_id.虽然您可能知道给定的 user_id 总是具有相同的名称和角色,但 PostgreSQL 无法知道这一点(除了您规范化数据之外),因此它需要有关在给定 user_id 中报告多个名称的内容的说明。 You need to include a dummy aggregation on the extra columns.您需要在额外的列上包含一个虚拟聚合。

select min(name) as name, min(role) as role, avg(score) as score, user_id 
    from user_score group by user_id

Rather than min , you could use max or string_agg(distinct ...) , or probably several other things而不是min ,您可以使用maxstring_agg(distinct ...) ,或者可能使用其他一些东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM