【问题标题】:AVG ( column1 ) while DISTINCT( column2 )AVG ( column1 ) 而 DISTINCT ( column2 )
【发布时间】:2017-12-27 07:26:01
【问题描述】:

我想计算一列的平均值,同时使用另一列作为不同的列,我不能使用 group by,因为它会影响其他一些数据,有什么方法可以在没有 group by 的情况下做到这一点

id      name      price
----------------------
1       name1     200
2       name2     200
3       name3     100
3       name3     100

我想要列价格的平均值,但有重复的行,所以我不能只写 AVG(price),也不能在价格上使用 distinct,而是我想在不使用 groupby 的情况下在 id 上使用 distinct

AVG( DISTINCT price)

【问题讨论】:

  • 请发布您的示例数据和预期结果。
  • 在撰写此评论时,您的问题完全无法回答。请向我们展示预期输出的示例输入。
  • 我有一张表,其中有一列 price ,我想使用 distinct 因为可能有重复的数据,显然我不能在 price 列上使用 distinct,而是我想使用 id 列作为 distinct
  • @RanjithM 基本上你想获得整个表格的平均价格和 id 列。那是
  • 对于相同的 ID,您需要平均价格、最高价格还是最低价格?喜欢 id 3 的价格 100 还是 200 ?

标签: mysql


【解决方案1】:

要从整个表和不同的 id 上获取平均价格,首先您需要排除基于相同 id 的重复数据,以下查询将选择每个 id 价格最高的单行,例如考虑到 id 3 的样本数据,有 3 个价格 100 和 200。如果您想选择最低价格,id 3 需要 200,然后将 a.price < b.price 更改为 a.price > b.price

select distinct a.*
from table1 a
left join table1 b on a.id = b.id
and a.price < b.price
where b.id is null;

一旦你有不同的数据,那么你可以申请avg()

select avg(price)
from (select distinct a.*
      from table1 a
      left join table1 b on a.id = b.id
      and a.price < b.price
      where b.id is null
) t;

或者

select  avg(a.price)
from table1 a
left join table1 b on a.id = b.id
and a.price < b.price
where b.id is null;

DEMO rextester 中有一些格式问题,所以这里是fiddle link

【讨论】:

    【解决方案2】:

    试试这个:

    SELECT AVG(DISTINCT price) FROM tableName;
    

    【讨论】:

    • 读取标题 'AVG ( column1 ) while DISTINCT( column2 )' avg 和其他列
    猜你喜欢
    • 1970-01-01
    • 2011-01-29
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 2018-02-20
    • 1970-01-01
    • 2021-06-06
    相关资源
    最近更新 更多