我有这个表需要(对于每一行)该记录的平均成本以及它所属类别的平均成本。
id category cost num ave_cost ave_cost_category
15117012 15 357.00 420 0.85 0.85
79030402 79 365.00 349 1.04 1.04
90125402 90 351.20 439 0.80 0.828
90125146 90 105.00 112 0.9375 0.828
ave_cost_category是我需要计算的列(它当前为null)。我在表格中有ave_cost数据。
答案 0 :(得分:1)
UPDATE MyTable
SET
ave_cost=cost/num,
ave_cost_category=t1.ave_cost_category
FROM MyTable
INNER JOIN
(
SELECT category,avg(ave_cost) as ave_cost_category
FROM MyTable
GROUP BY category
) t1 on MyTable.category = t1.category
JOIN中的内部查询计算整个类别的平均成本。
答案 1 :(得分:1)
WITH t
AS (SELECT SUM(cost) OVER (PARTITION BY category) AS c,
SUM(num) OVER (PARTITION BY category) AS n,
*
FROM yourtable)
UPDATE t
SET ave_cost = cost / num,
ave_cost_category = c / n
答案 2 :(得分:1)
您可以使用CTE(公用表格式)计算每个类别的平均成本,并从中更新您的表格:
;WITH CatCost AS
(
SELECT
Category,
SUM(Cost) / (1.0 * SUM(Num)) 'AvgCostCat'
FROM
dbo.YourTable
GROUP BY
Category
)
UPDATE dbo.YourTable
SET ave_cost_category = cc.AvgCostCat
FROM CatCost
WHERE dbo.YourTable.Category = cc.Category
答案 3 :(得分:1)
我建议在表格中创建两个计算列。
create function dbo.fnAveCostCat(@category int)
returns decimal(10,3)
as
begin
declare @ave decimal(10,3)
select @ave = AVG(t.cost/t.num)
from YourTable t
where t.category = @category
return @ave
end
go
alter table YourTable
add ave_cost as cost/num,
ave_cost_category as dbo.fnAveCostCat(category)
go
答案 4 :(得分:0)
也许这会对你有所帮助:
UPDATE yourTable SET ave_cost_category = x.avgcost FROM
yourTable inner JOIN (SELECT category, AVG(ave_cost) AS avgcost
FROM yourTable GROUP BY category) x
ON yourTable.category = x.category
答案 5 :(得分:-1)
更新您的平均费用,请尝试
update mytable set ave_cost = cost / num;
对于每个类别的平均成本,我不确定这是否适用于sql server,但你可以尝试:
update mytable set ave_cost_category = average
from mytable
inner join (
select category, avg(ave_cost) as average
from mytable
group by category
) as averages on table.category = averages.category