分组统计方法:用Group By
2005-01-20 09:19
281 查看
原贴: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 行)
表中三个字段
|---------------------------------------------|
| 产品 数量 单价 |
|=============================================|
| 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 行)
相关文章推荐
- 分组统计方法:用GroupBy
- oracle sum case when group by,同时使用,实现分组统计
- mongod统计(类似sql group by)aggregate函数使用方法
- 通过GROUP BY grouping sets提升数据分组统计效率
- mysql count group by统计条数方法
- C# List GroupBy 分组统计
- mysql count group by统计条数方法
- Hadoop实战-MapReduce之分组(group-by)统计(七)
- group by & count分组统计数量
- MySql按周/月/日分组统计数据的方法
- 采用灰度分组统计方法实现图像中值滤波
- Sql server Group by 统计数量 order by时间
- MySql按周/月/日分组统计数据的方法
- group分组之后要求统计count问题
- mysql之分组查询group by
- LINQ系列:LINQ to SQL Group by/Having分组
- sql group by分组 + 关联查询
- Sql group by 的使用方法
- Sql group by 分组取时间最新的一条数据
- mysql group by组内排序方法