在 Postgres 中计算与最大值的比率
Calculating ratio to maximum in Postgres
我在 Postgres 中有这个 table:
姓名 - varchar,体重和身高 - int4。我需要计算每条记录的重量与最大重量和高度与最大高度的比值。
到目前为止我只有这个:
select people.name, people.weight, people.height, people.weight/max(people.weight)
as weight_ratio, people.height/max(people.height) from people
但我收到此错误:column "people.name" must appear in the GROUP BY clause or be used in an aggregate function
我该如何解决这个问题?
使用MAX()
window函数:
SELECT name, weight, height,
weight / MAX(weight) OVER() weight_ratio,
height / MAX(height) OVER() height_ratio
FROM people
如果 weight
和 height
是整数,您还应该在除法之前乘以 1.0
,因为 Postgresql 执行整数之间的整数除法并将截断任何小数部分:
SELECT name, weight, height,
1.0 * weight / MAX(weight) OVER() weight_ratio,
1.0 * height / MAX(height) OVER() height_ratio
FROM people
我在 Postgres 中有这个 table:
姓名 - varchar,体重和身高 - int4。我需要计算每条记录的重量与最大重量和高度与最大高度的比值。
到目前为止我只有这个:
select people.name, people.weight, people.height, people.weight/max(people.weight)
as weight_ratio, people.height/max(people.height) from people
但我收到此错误:column "people.name" must appear in the GROUP BY clause or be used in an aggregate function
我该如何解决这个问题?
使用MAX()
window函数:
SELECT name, weight, height,
weight / MAX(weight) OVER() weight_ratio,
height / MAX(height) OVER() height_ratio
FROM people
如果 weight
和 height
是整数,您还应该在除法之前乘以 1.0
,因为 Postgresql 执行整数之间的整数除法并将截断任何小数部分:
SELECT name, weight, height,
1.0 * weight / MAX(weight) OVER() weight_ratio,
1.0 * height / MAX(height) OVER() height_ratio
FROM people