从现有列创建新列
Create a new column from existing columns
我想根据这个示例创建一个新列 table 但还有一个条件到目前为止我无法弄清楚,我想创建一个特定于每个城市的平均持股列。
Name | City | Holdings
Tom Jones | London | 42
Rick James| Paris | 83
Mike Tim | NY | 83
Milo James| London | 83
因此在此示例中 table 伦敦有多个实例,因此它将具有唯一值“62.5”,表示特定于城市列中的值的平均持有量。
Name | City | Holdings | City Avg. Holdings
Tom Jones | London | 42 | 62.5
Rick James| Paris | 36 | 36
Mike Tim | NY | 70 | 70
Milo James| London | 83 | 62.5
在 MySQL 8.0 中,这是具有 window 功能的 straight-forward:
select t.*, avg(holdings) over(partition by city) avg_city_holdings
from mytable t
在早期版本中,您可以加入:
select t.*, a.avg_city_holdings
from mytable t
left join (select city, avg(holdings) avg_city_holdings from mytable group by city) a
on a.city = t.city
我想根据这个示例创建一个新列 table 但还有一个条件到目前为止我无法弄清楚,我想创建一个特定于每个城市的平均持股列。
Name | City | Holdings
Tom Jones | London | 42
Rick James| Paris | 83
Mike Tim | NY | 83
Milo James| London | 83
因此在此示例中 table 伦敦有多个实例,因此它将具有唯一值“62.5”,表示特定于城市列中的值的平均持有量。
Name | City | Holdings | City Avg. Holdings
Tom Jones | London | 42 | 62.5
Rick James| Paris | 36 | 36
Mike Tim | NY | 70 | 70
Milo James| London | 83 | 62.5
在 MySQL 8.0 中,这是具有 window 功能的 straight-forward:
select t.*, avg(holdings) over(partition by city) avg_city_holdings
from mytable t
在早期版本中,您可以加入:
select t.*, a.avg_city_holdings
from mytable t
left join (select city, avg(holdings) avg_city_holdings from mytable group by city) a
on a.city = t.city