分组统计方法:用GroupBy

来源:互联网 发布:网络电视怎么找电视台 编辑:程序博客网 时间:2024/05/22 01:51
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

原贴: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语句。

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

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

droptable表

--结果:

(所影响的行数为5行)

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

(所影响的行数为2行)


<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>