在表/视图中添加字段

时间:2018-11-29 08:05:17

标签: sql sql-server

我想通过取多个值的平均值来计算sql表/视图中的平均值,并希望按另一列分组。

例如,在所附的excel工作表中,当块ID相同时,我想从SG(Calc)字段计算平均密度。

enter image description here

+-----------------------------------+-----------+--------------+
| BlockID                           | SG (Calc) | Ave. Density |
+-----------------------------------+-----------+--------------+
| SESS_5835_01_OXD_SAP_AL01         |      1.86 |              |
| SESS_5835_01_OXD_SAP_AL01         |      1.71 |              |
| SESS_5835_01_OXD_SAP_MG04         |      2.08 |              |
| SESS_5835_01_OXD_SAP_MG04         |      2.14 |              |
| KCD_5897.5_01_OXD_TRA_VG02        |      2.74 |              |
| KCD_5897.5_01_OXD_TRA_VG02        |      2.74 |              |
| KCD_5897.5_01_OXD_TRA_VG02        |      2.51 |              |
| KCD_5895_01_OXD_TRA_MG06          |      3.19 |              |
| KCD_5895_01_OXD_TRA_MG06          |      3.02 |              |
| SESS_58932.5_01_OXD_TRA_MG05      |      2.24 |              |
| SESS_58932.5_01_OXD_TRA_MG05      |      2.27 |              |
+-----------------------------------+-----------+--------------+

2 个答案:

答案 0 :(得分:0)

这将起作用:

select a.*,avg(SG(Calc)) from table_name a group by a.BlockID;

答案 1 :(得分:0)

您是否正在寻找窗口功能?

select a.*, avg(SG) over (partition by blockid) as avg_block_density
from t a ;