如何计算多列上的多个聚合

时间:2013-10-01 09:40:40

标签: sql sqlite

我想用aggragate函数创建我的表的摘要,例如max,min,avg 查询是这样的

select 'avg',avg(column1) as 'avg_resp',avg(col2) as 'ncount' from table
union all
select 'max',max(column1),max(col2) from table
union all 
select 'min',min(column1),min(col2) from table;

能以更好的方式完成吗? PS:我想将它用于REST API,所以我试图不转置/延长最终结果。

我当前代码中的REST API模型:

{ 
 avg_resp:[min,max,avg],
 ncount: [min,max,avg]
}

3 个答案:

答案 0 :(得分:1)

为什么不:

select 
  avg(column1) as 'avg_resp', 
  avg(col2)    as 'ncount',
  max(column1) AS Max1,
  max(col2)    AS MAx2, 
  min(column1) AS Min1,
  min(col2)    AS Min2
from table

答案 1 :(得分:1)

您可以将所有内容放在一个选择语句中

select avg(column1) as avg_resp,
       avg(col2) as ncount,
       max(column1) as max_col1,
       max(col2) as max_col2,
       min(column1) as min_col1,
       min(col2) as min_col2
from your_table

答案 2 :(得分:0)

是的,这是可能的

  select avg(column1) as avg_resp,
   avg(col2) as ncount,
   max(column1) as max_col1,
   max(col2) as max_col2,
   min(column1) as min_col1,
   min(col2) as min_col2
  from table