这SQL怎样写?

来源:百度知道 编辑:UC知道 时间:2024/06/06 05:38:01
表:品种 数量 价格 金额
6226# 103 52 5356
656# 209 57 11913
6226# 203 50 10150
6226# 202 50 10100
查询结果:
品种 数量 单价 金额 合计金额 平均价
6226# 103 52 5356 5356 52
656# 209 57 11913 11913 57
6226# 203 50 10150 15506 50.7
6226# 202 50 10100 25606 50.4

合计金额 是金额的总和,条件是品种一样
平均价 是单价的平均,条件是品种一样

如果你的表中有关键字或者序号之类的(如:id),用方法一
--------------------------------------------------------------
/*方法一*/
select 品种, 数量, 价格, 金额,
(select SUM(金额) from 表名 B where B.id <= A.id and B.品种 = A.品种) as 合计金额,
((select SUM(金额) from 表名 B where B.id <= A.id and B.品种 = A.品种) /
(select SUM(数量) from 表名 B where B.id <= A.id and B.品种 = A.品种)) as 平均价格
from 表名 A
---------------------------------------------------
如果没有序号或关键字之类的用下面的方法
/*方法二*/
select identity(int,1,1) as id, * into #t from 表名2
select 品种, 数量, 价格, 金额,
(select Sum(金额) from #t B where B.id <= A.id and B.品种 = A.品种) as 合计金额,
((select Sum(金额) from #t B where B.id <= A.id and B.品种 = A.品种) /
(select SUM(数量) from 表名 B where B.id <= A.id and B.品种 = A.品种))
as 平均价格
from #t A
drop table #t

如没有理解错的话,你是想做从1,1~2,1~3,1~4条记录的8次交叉查询,简单的SQL语句无法实现.写存储过程或者写程序实现应该没问题,
期待更好的解决办法!!!

Select sum(金额) from 表 group by 品种

Select avg(单价