我需要将数据聚合到应用程序,并找到数值列的最小值、最大值和平均值
我有什么
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个数字列,我需要将这些列的最小值、最大值和平均值的统计数据放入表中。有没有什么方法可以做到这一点,而不是手动编写列名来获得平均值、最小值和最大值
它们都是数字,所以你可以做:
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;
这会将值放在每列的单独行中。
这是一个rextester。
我喜欢Gordon Linoff的答案,但我一直觉得无法在内联表定义中计算表达式outer(.(。
所以我的方法是用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 = "nUNIONn".join(query_list)
spark.sql(query).show()