Postgresql聚合报错:column XXX must appear in the GROUP BY clause or be used in an aggregate function

1 reference article

An article is written very clearly, you can refer to: https://zhuanlan.zhihu.com/p/457341706

2 Reason analysis:

The intention of aggregation is to get some attribute values ​​of a collection: maximum value, minimum value, average value, sum. . . .
These attributes are the new data calculated by the original column, and there will be problems when we directly refer to the unprocessed original table data

3 solve

3.1 For example:

Find the aggregation of the expenses of 3 people

user_name cost
tom 23
jessy 12
tom 3

3.2 Query statement

select 
	user_name,
	cost,
from t_cost
group by user_name

error:column cost must appear in the GROUP BY clause or be used in an aggregate function

3.3 Cause analysis:

What does this core mean at this time ? Which cost? There is a problem with understanding aggregation
unless it says: total cost, average cost, maximum cost, and minimum cost . . . This kind of statistics, so the logic is no problem

3.4 Solution:

# 聚合求平均值
select 
	user_name,
	avg(cost),
from t_cost
group by user_name

# 聚合求总和
select 
	user_name,
	sum(cost),
from t_cost
group by user_name

# 聚合求最大值
select 
	user_name,
	max(cost),
from t_cost
group by user_name

Guess you like

Origin blog.csdn.net/qq_42647903/article/details/127979751