根据Key查找平均值

时间:2017-09-05 08:46:23

标签: sql sql-server

我有一张表和这样的值

create table Mytable (Cost money, NKey int, AvgBasedOnkey money)

insert into Mytable(Cost,NKey) values
    (20 ,1) ,
    (7  ,2) ,
    (7  ,2) ,
    (40 ,3) ,
    (40 ,3) ,
    (40 ,3) ,
    (5  ,3) ,
    (6  ,4) ,
    (8  ,4) `

enter image description here

我希望根据AvgBasedOnKey值在NKey列中更新平均费用,如图所示,例如

(40 + 40 + 40 + 5) / 4 = 31.25(因为关键数字3发生了4次)

帮我提供正确的代码

7 个答案:

答案 0 :(得分:3)

在SQL Server中,有一种简单的方法可以执行您想要的操作。您可以使用AVG函数的窗口版本:

SELECT Cost, NKey, AVG(Cost) OVER (PARTITION BY NKey)
FROM mytable

Demo here

此版本的AVG可从SQL Server 2008开始提供。它只是计算其参数在OVER子句

中指定的分区的平均值

答案 1 :(得分:2)

尝试使用外部应用此解决方案:

drop table if exists dbo.MyTable;

create table dbo.Mytable (Cost money, NKey int, AvgBasedOnkey money)

insert into dbo.Mytable(Cost,NKey) values
(20,1) ,
(7  ,2) ,
(7  ,2) ,
(40 ,3) ,
(40 ,3) ,
(40 ,3) ,
(5  ,3) ,
(6  ,4) ,
(8  ,4)


select
*
from dbo.Mytable mt
    outer apply (
            select
                avg(tmt.Cost) as AverageCost
            from dbo.Mytable tmt
            where tmt.NKey = mt.NKey
    ) t

答案 2 :(得分:1)

select  *, sum(Cost) over(partition by NKey) 
         / count(*) over(partition by NKey) as AvgBasedOnKey
from    Mytable

答案 3 :(得分:1)

下面的查询将生成按键的AvgBsedOnKey结果,您可以将其加入原始表格

SELECT 
Key,
SUM(Cost)/COUNT(Cost) as AvgBasedOnKey
FROM Mytable
GROUP BY Key

答案 4 :(得分:0)

您可以通过使用连接更新表来使用AVG()进行平均计算的子查询来完成此操作。

create table MyTable (Cost money, NKey int, AvgBasedOnkey money null)

insert into MyTable ( Cost, NKey ) values
    (20,1) ,
    (7  ,2) ,
    (7  ,2) ,
    (40 ,3) ,
    (40 ,3) ,
    (40 ,3) ,
    (5  ,3) ,
    (6  ,4) ,
    (8  ,4) 


update t set t.AvgBasedOnkey = calc.AvgCost
    from MyTable t
    inner join (
        -- get average grouped on key
        select NKey, AVG(Cost) as AvgCost from MyTable group by NKey
    ) calc on t.NKey = calc.NKey

SELECT * FROM MyTable

答案 5 :(得分:0)

您可以按此键计算平均值

SELECT
            [Key],
            AVG([Cost]) [Average based on Key]
    FROM
            [MyTable]
    GROUP BY
            [Key];

如果你真的需要为每一行重复那些平均值(为什么),你可以像这样加入。

SELECT
            T.[Cost],
            T.[Key],
            A.[Avg] [Average based on Key]
    FROM
            [MyTable] T
        JOIN
            (
                SELECT
                            [Key],
                            AVG([Cost]) [Avg]
                    FROM
                            [MyTable]
                    GROUP BY
                            [Key]
            ) A
                ON A.[Key] = T.[Key];

答案 6 :(得分:0)

应该像以下一样轻松工作:

    UPDATE upd
       SET upd.AvgBasedOnkey = result.AvgCost
      FROM Mytable upd
INNER JOIN (
         SELECT AVG(Cost) AS AvgCost
               ,NKey
           FROM Mytable
         GROUP BY NKey   
           ) result
        ON result.NKey = upd.NKey