Sql;select 平均值和同一列中的一个值

Sql;select average and one value from same column

如何将同一列中的平均值和另一个值放入新 table 中的两个不同列中?

我有这个:

Person_ID col2         col3_values
1         101010A      20000
1         101010B      30000
2         101010A      25000
2         101010B      30000
3         101010A      22000
3         101010B      24000

我想要一个 table 平均 col3_values 与 ID:s 来自 col1_ID (1,2,3) 然后将这个平均值与一列进行比较持有 col1_ID: 像这样的值:

col2        AVG(value personID_1-3)  Value PersonID_1
101010 A    22333                    20000
101010 B    28000                    30000

我尝试了很多代码,但没有任何效果。有人可以帮我吗?如果这有效,我将不胜感激,如果我也能得到第四列,显示平均列和第三列之间的差异,其中包含 ID_1:s 个值。

有很多方法可以做到这一点,一种是使用 outer apply 结构:

select 
    col2, 
    AVG(t.col3_values) as "AVG(value personID_1-3)", 
    a.col3_values as "Value PersonID_1",
    AVG(t.col3_values) - a.col3_values as "Difference"
from your_table t 
outer apply (
    select col3_values from your_table  where Person_ID = 1 and t.col2 = col2
) a
group by col2, a.col3_values

或者您可以使用相关子查询:

select 
    col2, 
    AVG(t.col3_values) as "AVG(value personID_1-3)", 
    (
      select col3_values from your_table where Person_ID = 1 and t.col2 = col2
    ) as "Value PersonID_1"
from your_table t 
group by col2

示例输出:

Query 1:
col2                 AVG(value personID_1-3) Value PersonID_1 Difference
-------------------- ----------------------- ---------------- -----------
101010A              22333                   20000            2333
101010B              28000                   30000            -2000


Query 2:    
col2                 AVG(value personID_1-3) Value PersonID_1
-------------------- ----------------------- ----------------
101010A              22333                   20000
101010B              28000                   30000