SQL 等同于 pandas 'transform' 是什么?

What is the SQL equivalent to pandas 'transform'?

假设您有以下 SQL table:

  A  B  C  
  2  1  4       
  3  4  5     
  3  1  1    
  1  4  0       
  5  0  1 

并且您想要 add/show 一个包含列 A 的平均值(或任何其他聚合函数)的列,用于列 B 的每个不同值。您想要保留所有列。所以结果看起来像这样:

  A  B  C    avg(A)|B
  2  1  4       2.5
  3  4  5       2.0
  3  1  1       2.5
  1  4  0       2.0
  5  0  1       5.0

据我所知,在 pandas 中执行此操作的最佳方法是:

>>> df['avg(A)|B'] = df.groupby('B')['A'].transform('mean')
>>> df
   A  B  C  avg(A)|B
0  2  1  4       2.5
1  3  4  5       2.0
2  3  1  1       2.5
3  1  4  0       2.0
4  5  0  1       5.0

在 SQL 你会怎么做?可以避免使用 JOIN 吗?

您可以连接到派生的 table,其中包含 b

的每个分组的聚合值
select * from mytable t1
join (
    select avg(a), b
    from mytable
    group by b
) t2 on t2.b = t1.b

或使用子查询

select *, (select avg(a) from mytable t2 where t2.b = t1.b)
from mytable t1

问题被标记为 mysql 和 psql,所以我不确定您使用的是哪个数据库。但是在 postgres 上你可以使用 window 函数

select *, avg(a) over (partition by b) 
from mytable