gpt4 book ai didi

sql - 根据 Key 求平均值

转载 作者:行者123 更新时间:2023-12-01 13:22:24 24 4
gpt4 key购买 nike

我有一个表和这样的值

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

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

(40 + 40 + 40 + 5)/4 = 31.25(因为键号 3 出现了 4 次)

帮我改正代码

最佳答案

在 SQL Server 中,有一种简单的方法可以做你想做的事。您可以使用 AVG 函数的窗口版本:

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

Demo here

这个版本AVG从 SQL Server 2008 开始可用。它只是计算其参数在 OVER 子句

中指定的分区上的平均值

关于sql - 根据 Key 求平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46050716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com