现有表 A:
字段1为字符型,字段2为字符型,字段3为数值型,字段4为数值型
——————————————————————
表A内容如下。
-------------------------------------------
字段1 字段2 字段3 字段4
2001 wm 12.5 1
2001 wm 12.5 1
2001 wm 0 1
2001 wm 14 1
2002 wm 11 1
2002 wm 12 1
2002 wm 13 1现在要求以下结果:
-------------------------------------------
字段1 字段3的平均值(不把等于0的算在内) 字段4的和
2001 13.5 4
2002 12 3
-------------------------------------------
请高手们指教
字段1为字符型,字段2为字符型,字段3为数值型,字段4为数值型
——————————————————————
表A内容如下。
-------------------------------------------
字段1 字段2 字段3 字段4
2001 wm 12.5 1
2001 wm 12.5 1
2001 wm 0 1
2001 wm 14 1
2002 wm 11 1
2002 wm 12 1
2002 wm 13 1现在要求以下结果:
-------------------------------------------
字段1 字段3的平均值(不把等于0的算在内) 字段4的和
2001 13.5 4
2002 12 3
-------------------------------------------
请高手们指教
select a.字段1,字段3的平均值,sum(字段4)字段4的和
from
(select 字段1 ,avg(字段3) 字段3的平均值 from A where 字段3>0 group by 字段1)b,a
where a.字段1=b.字段1
group by a.字段1
from a
group by 字段1
group by 字段1
(case when
字段3<>0 then
字段3
else
null
end) AS 字段3的平均值,
sum(字段4) AS 字段4的和 from A
group by 字段1
Select average.字段1,average.字段3的平均值,summation.字段4的和 From
(--求字段3平均值
Select 字段1,Avg(字段3) AS 字段3的平均值 From A Where 字段3>0 Group By 字段1
) AS average
Inner Join
(--求字段4的和
Select 字段1,Sum(字段4) AS 字段4的和 From A Group By 字段1
) AS summation On average.字段1=summation.字段1
Order by average.字段1--如果我对你的说明理解正确的话,应该是这样的
group by 字段1
3楼是正解,因为SQL SERVER 的avg不会将NULL纳入计算,自然就将=0的给排除了。
from t
group by 字段1
insert into @aa select '2001', 'wm', 12.5 ,1
insert into @aa select '2001', 'wm', 12.5 ,1
insert into @aa select '2001', 'wm', 0 ,1
insert into @aa select '2001', 'wm', 14 ,1
insert into @aa select '2002', 'wm', 11 ,1
insert into @aa select '2002', 'wm', 12 ,1
insert into @aa select '2002', 'wm', 13,1 select [字段1] ,sum([字段3])/sum(case 字段3 when 0 then 0 else 1 end) ,sum([字段4]) from @aa group by [字段1]
--结果
(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)
字段1
---------- --------------------------------------- -----------
2001 13.000000 4
2002 12.000000 3(2 row(s) affected)