显示具有最小平均SQL Server的组

时间:2016-10-02 18:27:54

标签: sql-server average

我需要创建一个查询,返回具有最小列平均值的组。

您能否告诉我如何做到这一点? 提前致谢

4 个答案:

答案 0 :(得分:0)

     Select Groupname,avg(column) as average
        into #temptable
        from tablename
        group by groupname

        Declare @lowvalue INT

        select @lowvalue = top 1 [average] from #temptable order by average

        select * from #temptable where average = @lowvalue

    drop #temptable

答案 1 :(得分:0)

cte将返回每组的平均值。然后从cte中选择平均最小值。然后加入两个cte以选择平均值最低的组。

with cte as (
Select Grp, AVG(Col) as ColAvg 
From MyTable
Group by Grp
), cte2 as (
  select Min(ColAvg) as MinAvg from ate
)   
select a.* from cte as a
outer apply cte2 as b 
Where a.ColAvg = b.MinAvg;

答案 2 :(得分:0)

int main()
{
    int a,b,next,last,i;
    printf("Enter the first Value:");
    scanf("%d",&a);
    printf("Enter the second Value:");
    scanf("%d",&b);
    printf("Enter the length of Fab. series:");
    scanf("%d",&last);
    printf("%d,%d,",a,b);
    for (i=3; i<= last; i++)
    {
    next = a + b;
    if(i<last)
    printf("%d,",next);
    else
    printf("%d",next);
    a = b;
    b = next;
    }
    return 0;
}

简单但效率不高。

答案 3 :(得分:0)

您可以计算每组的平均值,然后您可以计算最小平均值,并选择所有具有最小平均值的组。这是CTE的解决方案:

with avg_per_group as (
select
  grp, avg(val) as avg_val
from
  tablename
group by
  grp
)
select grp
from avg_per_group
where
  avg_val = (select min(avg_val) from avg_per_group);

或者您可以使用窗口函数来计算排名(基于平均列)并选择排名为1的所有行:

with avg_per_group as (
select
  grp, avg(val) as avg_val
from
  tablename
group by
  grp
),
avg_per_group_rank as (
select
  grp, avg_val, rank() over (order by avg_val) r
from
  avg_per_group
)
select
  grp, avg_val
from
  avg_per_group_rank
where
  r=1;

请查看工作小提琴here