sql查询以获取平均值之和

watbbzwu  于 2021-07-26  发布在  Java
关注(0)|答案(5)|浏览(311)

需要sql查询才能得到以下结果
考虑表

Column1  || Column2 || Column3
    H1       A1          10
    H1       A1          10
    H1       A2          30
    H1       A2          30
    H1       A2          30

我希望查询为第2列的平均值查找第1列的和
例子

Column1 || Column 3
      H1      40            (Average of A1 + A2 i.e (10 + 30)
qyyhg6bp

qyyhg6bp1#

SELECT column1, SUM(Avg_col3) AS total
FROM (
    SELECT column1, column2, AVG(column3) AS avg_col3
    FROM t
    GROUP BY column1, column2
) A
GROUP BY column1;
ljo96ir5

ljo96ir52#

您可以通过两个聚合来实现这一点:

SELECT Column1, SUM(Column3Avg) AS Column3
FROM
(
    SELECT Column1, Column2, AVG(Column3) AS Column3Avg
    FROM yourTable
    GROUP BY Column1, Column2
) t
GROUP BY
    Column1;

此方法首先通过第一列和第二列进行聚合,以生成如下所示的中间结果:

Column1 | Column2 | Column3Avg
H1      | A1      | 10
H1      | A2      | 30

然后,我们单独用第一列对上述数据进行聚合,并对第3列的平均值求和。

628mspwn

628mspwn3#

如果有这样重复的数字,你的数据模型看起来真的一团糟。我建议:

select column1, sum(column3)
from (select distinct column1, column2, column3
      from t
     ) t
group by column1;
dphi5xsq

dphi5xsq4#

为了 SQL Server 使用以下查询获得所需的结果。

WITH CTE AS (
    SELECT  Column1,
            AVG(Column3) AS Column3
    FROM Table1
    GROUP BY Column1, Column2
)
SELECT Column1, SUM(Column3) AS Column3
FROM CTE
GROUP BY Column1
k4aesqcs

k4aesqcs5#

请运行以下代码。你会得到你的结果的。

Select *
into #tmp
from (
    select 'h1' as Column1, 'A1' as Column2, 10 as Column3
    union all
    select 'h1' as Column1, 'A1' as Column2, 10 as Column3
    union all
    select 'h1' as Column1, 'A2' as Column2, 30 as Column3
    union all
    select 'h1' as Column1, 'A2' as Column2, 30 as Column3
    union all
    select 'h1' as Column1, 'A2' as Column2, 30 as Column3
)r
select * from #tmp
Select r.Column1, sum(r.Column3) Column3
from (
    select Column1, Column2, avg(Column3) Column3
    from #tmp
    group by Column1, Column2
 )r
 group by r.Column1

相关问题