繁体   English   中英

如何聚合数据并查找 postgresql 中数字列的最小值、最大值、平均值

[英]How to aggregate data and find min,max,avg of numeric columns in postgresql

我需要将数据聚合到应用程序并找到数字列的最小值、最大值、平均值

我拥有的

  Application  income   score_1
    ax          800        77
    ax          900        72
    ax          700        62    
    ax          600        55    

我需要的

  Application  min(income) max(income)    avg(income)  min(score_1) max(score_1)    avg(score_1)
    ax          800           900              750        62           77           224.75         

我可以将查询写为

select min(income),max(income),avg(income),min(score_1),max(score_1),avg(score_1)
from table name group by application; --IT WORKS..!!

但在表中我有 20 个数字列,我需要将这些列的最小值、最大值、平均值的统计信息放入表中。 有什么方法可以完成这项工作,而不是手动编写列名来获取 avg、min、max

它们都是数字,因此您可以执行以下操作:

select application, which,
       min(val), max(val), avg(val)
from t, lateral
     (values ('income', income), ('score_1', score_1)) v(which, val)
group by application, which;

这会将值放在每一列的单独行上。

是一个学期。

我喜欢 Gordon Linoff 的回答,但我不断收到cannot evaluate expression outer(.) in inline table definition

所以我的方法是使用 python 进行大查询:

columns = ['income','score_1']
functions = ['max','avg','min']

query_list = []
for func in functions:
  subquery = [f"SELECT '{func}'"]
  for col in columns:
    subquery.append(f"    ROUND({func}({col}),2) as {col}")
  query_list.append(",\n".join(subquery) + "\nFROM table_name")
query = "\nUNION\n".join(query_list)

spark.sql(query).show()

暂无
暂无

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

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