[英]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_id
、 role
和name
。 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.我只会在这个表中留下
score
和user_id
,将user_id
、 role
和name
移动到另一个并使用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
,您可以使用max
或string_agg(distinct ...)
,或者可能使用其他一些东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.