【问题标题】:Need to sort first column by values in a dataset and then find average需要按数据集中的值对第一列进行排序,然后找到平均值
【发布时间】:2020-02-16 15:36:05
【问题描述】:

我的数据集中有一些值。有3列。 第 1 列的值为 1,1,3,4,5,5,6,7,7,7,7。我需要对列进行排序,然后应用平均值。 1,1 表示索引为 1 和 1 的两行。我需要对其余列的值进行平均,即每行的第 2 列和第 3 列。 对于 5,5 中的数据类似,依此类推。能够排序但无法管理一般问题..

【问题讨论】:

  • 您使用的是什么品牌的 RDMS?

标签: sql sorting


【解决方案1】:

ROW_NUMBER() 应该为您进行排序, (col1+col2+col3)/3 应该为您平均。对于可为空的列,您需要对代码进行一些更改。

SELECT t1.rownumber, (t1.col1 + t2.col2 + t3.col3)/3 as "AVG"
FROM (SELECT ROW_NUMBER() OVER(ORDER BY col1 DESC) AS rownumber, col1 FROM MyTable) t1
INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY col2 ASC) AS rownumber, col2 FROM MyTable) as t2 on t1.rownumber = t2.rownumber
INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY col3 ASC) AS rownumber, col3 FROM MyTable) as t3 on t1.rownumber = t3.rownumber

【讨论】:

    【解决方案2】:

    您的问题听起来像是描述聚合的复杂方式。这是你想要的吗?

    select col1, avg(col2), avg(col3)
    from t
    group by col1;
    

    如果您想要每行的平均值,请使用窗口函数:

    select col1,
           avg(col2) over (partition by (col1),
           avg(col3) over (partition by (col1)
    from t;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-02
      • 2015-07-16
      • 2021-05-05
      • 1970-01-01
      • 2020-07-07
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多