select [编号], [加权平均值]=(sum([数量]*[单价])+0.0)/sum([数量]) from a group by [编号] where [编号]='001'
declare @tb table ( [编号] varchar(10), [数量] int, [单价] int ) insert @tb select '001',1,100 union select '002',1,120 union select '003',5,300 union select '001',2,110 union select '002',1,110 --查询 select [编号], [加权平均值]=(sum([数量]*[单价])+0.0)/sum([数量]) from @tb group by [编号] --where [编号]='001' --结果 /* 编号 加权平均值 ---------- ------------------------- 001 106.67 002 115.00 003 300.00(所影响的行数为 3 行)*/
select [编号], [加权平均值]=(sum([数量]*[单价]))/(sum([数量])+0.0) from a group by [编号]
为什么 (sum([数量])+0.0) 要加 0.0?
--测试环境 declare @表a table (编号 varchar(3),数量 int ,单价 money) insert into @表a select '001',1,100 union all select '002',1,120 union all select '003',5,300 union all select '001',2,110 union all select '002',1,110 --查询语句 select 编号,加权平均单价=sum(单价*数量)/sum(数量) from @表a group by 编号 --结果 编号 平均单价 ---- --------------------- 001 106.6666 002 115.0000 003 300.0000(所影响的行数为 3 行)
[加权平均值]=(sum([数量]*[单价])+0.0)/sum([数量])
from a
group by [编号]
where [编号]='001'
(
[编号] varchar(10),
[数量] int,
[单价] int
)
insert @tb
select '001',1,100 union
select '002',1,120 union
select '003',5,300 union
select '001',2,110 union
select '002',1,110 --查询
select [编号],
[加权平均值]=(sum([数量]*[单价])+0.0)/sum([数量])
from @tb
group by [编号]
--where [编号]='001'
--结果
/*
编号 加权平均值
---------- -------------------------
001 106.67
002 115.00
003 300.00(所影响的行数为 3 行)*/
[加权平均值]=(sum([数量]*[单价]))/(sum([数量])+0.0)
from a
group by [编号]
declare @表a table (编号 varchar(3),数量 int ,单价 money)
insert into @表a select '001',1,100
union all select '002',1,120
union all select '003',5,300
union all select '001',2,110
union all select '002',1,110
--查询语句
select 编号,加权平均单价=sum(单价*数量)/sum(数量)
from @表a
group by 编号
--结果
编号 平均单价
---- ---------------------
001 106.6666
002 115.0000
003 300.0000(所影响的行数为 3 行)