分组统计方法:用Group By

来源:互联网 发布:解压密码破解软件 编辑:程序博客网 时间:2024/04/27 22:08

原贴:http://community.csdn.net/Expert/topic/3739/3739565.xml?temp=.7632105
表中三个字段
|---------------------------------------------|
|  产品             数量                单价  |
|=============================================|
|  A                3                    20   |
|  A                4                    25   |
|  A                2                    30   |
|  B                6                    85   |
|  B                3                    96   |
|---------------------------------------------|

现在想得到以下结果:
    产品   平均价
     A       ******
     B       ******
注意:一种商品一个平均价

平均数算法:
A的平均价数= (3 * 20)+ (4 * 25)+ (2 * 30)/(3+4+2),B的平均值也如A。

求该SQL语句。

create table 表(产品  varchar(5),数量  int,单价 decimal(4,2))
insert 表 select 'A',3,20
union all select 'A',4,25
union all select 'A',2,30
union all select 'B',6,85
union all select 'B',3,96

select 产品,cast(sum(isnull(单价,0)*isnull(数量,0))/sum(数量) as decimal(4,2)) as '平均值' from 表 group by 产品

drop table 表

--结果:

(所影响的行数为 5 行)

产品    平均值   
----- ------
A     24.44
B     88.67

(所影响的行数为 2 行)

原创粉丝点击